asyncredux-persistence

0
0
Source

Implement local state persistence using Persistor. Covers creating a custom Persistor class, implementing `readState()`, `persistDifference()`, `deleteState()`, using LocalPersist helper, throttling saves, and pausing/resuming persistence with app lifecycle.

Install

mkdir -p .claude/skills/asyncredux-persistence && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6209" && unzip -o skill.zip -d .claude/skills/asyncredux-persistence && rm skill.zip

Installs to .claude/skills/asyncredux-persistence

About this skill

Overview

AsyncRedux provides state persistence by passing a persistor object to the Store. This maintains app state on disk, enabling restoration between sessions.

Store Initialization with Persistor

At startup, read any existing state from disk, create default state if none exists, then initialize the store:

var persistor = MyPersistor();

var initialState = await persistor.readState();

if (initialState == null) {
  initialState = AppState.initialState();
  await persistor.saveInitialState(initialState);
}

var store = Store<AppState>(
  initialState: initialState,
  persistor: persistor,
);

The Persistor Abstract Class

The Persistor<St> base class defines these methods:

abstract class Persistor<St> {
  /// Read persisted state, or return null if none exists
  Future<St?> readState();

  /// Delete state from disk
  Future<void> deleteState();

  /// Save state changes. Provides both newState and lastPersistedState
  /// so you can compare them and save only the difference.
  Future<void> persistDifference({
    required St? lastPersistedState,
    required St newState
  });

  /// Convenience method for initial saves
  Future<void> saveInitialState(St state) =>
    persistDifference(lastPersistedState: null, newState: state);

  /// Controls save frequency. Return null to disable throttling.
  Duration get throttle => const Duration(seconds: 2);
}

Creating a Custom Persistor

Extend the abstract class and implement the required methods:

class MyPersistor extends Persistor<AppState> {

  @override
  Future<AppState?> readState() async {
    // Read state from disk (e.g., from SharedPreferences, file, etc.)
    return null;
  }

  @override
  Future<void> deleteState() async {
    // Delete state from disk
  }

  @override
  Future<void> persistDifference({
    required AppState? lastPersistedState,
    required AppState newState,
  }) async {
    // Save state to disk.
    // You can compare lastPersistedState with newState to save only changes.
  }

  @override
  Duration get throttle => const Duration(seconds: 2);
}

Throttling

The throttle getter controls how often state is saved. All changes within the throttle window are collected and saved in a single call. The default is 2 seconds.

// Save at most every 5 seconds
@override
Duration get throttle => const Duration(seconds: 5);

// Disable throttling (save immediately on every change)
@override
Duration? get throttle => null;

Forcing Immediate Save

Dispatch PersistAction() to save immediately, bypassing the throttle:

store.dispatch(PersistAction());

Pausing and Resuming Persistence

Control persistence with these store methods:

store.pausePersistor();           // Pause saving
store.persistAndPausePersistor(); // Save current state, then pause
store.resumePersistor();          // Resume saving

App Lifecycle Integration

Pause persistence when the app goes to background and resume when it becomes active. Create an AppLifecycleManager widget:

class AppLifecycleManager extends StatefulWidget {
  final Widget child;

  const AppLifecycleManager({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  _AppLifecycleManagerState createState() => _AppLifecycleManagerState();
}

class _AppLifecycleManagerState extends State<AppLifecycleManager>
    with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState lifecycle) {
    store.dispatch(ProcessLifecycleChange_Action(lifecycle));
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

Create an action to handle lifecycle changes:

class ProcessLifecycleChange_Action extends ReduxAction<AppState> {
  final AppLifecycleState lifecycle;

  ProcessLifecycleChange_Action(this.lifecycle);

  @override
  Future<AppState?> reduce() async {
    if (lifecycle == AppLifecycleState.resumed ||
        lifecycle == AppLifecycleState.inactive) {
      store.resumePersistor();
    } else if (lifecycle == AppLifecycleState.paused ||
        lifecycle == AppLifecycleState.detached) {
      store.persistAndPausePersistor();
    } else {
      throw AssertionError(lifecycle);
    }
    return null;
  }
}

Wrap your app with the lifecycle manager:

StoreProvider<AppState>(
  store: store,
  child: AppLifecycleManager(
    child: MaterialApp( ... ),
  ),
)

LocalPersist Helper

The LocalPersist class simplifies disk operations for Android/iOS. It works with simple object structures containing only primitives, lists, and maps.

import 'package:async_redux/local_persist.dart';

// Create instance with a file name
var persist = LocalPersist("myFile");

// Save data
List<Object> simpleObjs = [
  'Hello',
  42,
  true,
  [100, 200, {"name": "John"}],
];
await persist.save(simpleObjs);

// Load data
List<Object> loaded = await persist.load();

// Append data
List<Object> moreObjs = ['more', 'data'];
await persist.save(moreObjs, append: true);

// File operations
int length = await persist.length();
bool exists = await persist.exists();
await persist.delete();

// JSON operations for single objects
await persist.saveJson(simpleObj);
Object? simpleObj = await persist.loadJson();

Note: LocalPersist only supports simple objects. For complex nested structures or custom classes, you need to implement serialization yourself (e.g., using JSON encoding with toJson/fromJson methods).

References

URLs from the documentation:

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.