Flutter持久化状态管理插件redux_persist_flutter的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter持久化状态管理插件redux_persist_flutter的使用

简介

redux_persist_flutter 是一个用于Flutter的持久化存储引擎,它支持将Redux的状态保存到应用的文档目录或SharedPreferences中。这使得应用程序可以在重启后恢复之前的状态。

主要特性

  • 支持保存到应用文档目录(默认推荐)和SharedPreferences。
  • 支持Flutter Web,通过SharedPreferences进行存储。
  • 可以设置自定义的文件名或SharedPreferences键。
  • 提供了处理Android备份行为的功能。

安装

pubspec.yaml文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  redux: ^5.0.0
  redux_persist: ^0.6.0
  redux_persist_flutter: ^0.7.0
  shared_preferences: ^2.0.15

使用方法

创建Persistor

首先创建一个Persistor实例,并指定存储位置和序列化方式:

final persistor = Persistor<AppState>(
  storage: FlutterStorage(),
  serializer: JsonSerializer<AppState>(AppState.fromJson),
);

加载初始状态

建议在调用runApp之前加载初始状态,以便Flutter显示启动画面直到我们准备好渲染:

void main() async {
  // 加载初始状态
  final initialState = await persistor.load();

  final store = Store<AppState>(
    reducer,
    initialState: initialState ?? AppState(),
    middleware: [persistor.createMiddleware()],
  );

  runApp(App(
    store: store,
  ));
}

定义状态类和Reducer

定义一个包含计数器的状态类,并实现相应的Reducer来处理状态变化:

class AppState {
  final int counter;

  AppState({this.counter = 0});

  AppState copyWith({int counter}) => AppState(counter: counter ?? this.counter);

  static AppState fromJson(dynamic json) => AppState(counter: json["counter"] as int);

  dynamic toJson() => {'counter': counter};
}

class IncrementCounterAction {}

AppState reducer(AppState state, Object action) {
  if (action is IncrementCounterAction) {
    return state.copyWith(counter: state.counter + 1);
  }
  return state;
}

构建UI

使用StoreProvider包裹整个应用程序,并通过StoreConnector连接状态与UI组件:

class App extends StatelessWidget {
  final Store<AppState> store;

  const App({Key key, this.store}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreProvider(
      store: store,
      child: MaterialApp(title: 'Redux Persist Demo', home: HomePage()),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Redux Persist demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            StoreConnector<AppState, String>(
              converter: (store) => store.state.counter.toString(),
              builder: (context, count) => Text(
                '$count',
                style: Theme.of(context).textTheme.display1,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: StoreConnector<AppState, VoidCallback>(
        converter: (store) => () => store.dispatch(IncrementCounterAction()),
        builder: (_, increment) => FloatingActionButton(
          onPressed: increment,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

存储位置

你可以选择将数据保存到应用文档目录(默认推荐)或者SharedPreferences:

// 使用SharedPreferences
FlutterStorage(location: FlutterSaveLocation.sharedPreferences);

// 使用文档文件
FlutterStorage(location: FlutterSaveLocation.documentFile);

对于Flutter Web项目,默认会使用SharedPreferences作为存储机制。

设置键值

可以通过传递key参数给FlutterStorage来为文件名或SharedPreferences键提供自定义名称:

FlutterStorage(key: 'my_custom_key');

Android备份问题

为了避免Android系统保留已卸载应用的数据,可以在android/app/src/main/AndroidManifest.xml中添加以下配置:

<application
  ...
  android:allowBackup="false"
  ...>
</application>

示例代码

完整的示例代码如下所示:

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:redux_persist/redux_persist.dart';
import 'package:redux_persist_flutter/redux_persist_flutter.dart';

void main() async {
  // 创建Persistor
  final persistor = Persistor<AppState>(
    storage: FlutterStorage(),
    serializer: JsonSerializer<AppState>(AppState.fromJson),
  );

  // 加载初始状态
  final initialState = await persistor.load();

  final store = Store<AppState>(
    reducer,
    initialState: initialState ?? AppState(),
    middleware: [persistor.createMiddleware()],
  );

  runApp(App(
    store: store,
  ));
}

class AppState {
  final int counter;

  AppState({this.counter = 0});

  AppState copyWith({int counter}) => AppState(counter: counter ?? this.counter);

  static AppState fromJson(dynamic json) => AppState(counter: json["counter"] as int);

  dynamic toJson() => {'counter': counter};
}

class IncrementCounterAction {}

AppState reducer(AppState state, Object action) {
  if (action is IncrementCounterAction) {
    return state.copyWith(counter: state.counter + 1);
  }
  return state;
}

class App extends StatelessWidget {
  final Store<AppState> store;

  const App({Key key, this.store}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreProvider(
      store: store,
      child: MaterialApp(title: 'Redux Persist Demo', home: HomePage()),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Redux Persist demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            StoreConnector<AppState, String>(
              converter: (store) => store.state.counter.toString(),
              builder: (context, count) => Text(
                '$count',
                style: Theme.of(context).textTheme.display1,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: StoreConnector<AppState, VoidCallback>(
        converter: (store) => () => store.dispatch(IncrementCounterAction()),
        builder: (_, increment) => FloatingActionButton(
          onPressed: increment,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

以上就是关于redux_persist_flutter插件的基本使用介绍,希望对您有所帮助!如果有任何问题或需要进一步的帮助,请随时提问。


更多关于Flutter持久化状态管理插件redux_persist_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter持久化状态管理插件redux_persist_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用redux_persist_flutter插件进行持久化状态管理的示例代码。redux_persist_flutter是一个用于Redux状态管理的持久化库,可以将Redux存储的状态保存到磁盘上,并在应用重新启动时恢复。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加redux_persist_flutterredux依赖:

dependencies:
  flutter:
    sdk: flutter
  redux: ^5.0.0
  redux_persist_flutter: ^0.10.0 # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 定义Redux Store

创建一个Redux Store,并定义初始状态和reducer。

import 'package:redux/redux.dart';
import 'package:redux_persist_flutter/redux_persist_flutter.dart';
import 'package:redux_persist/redux_persist.dart';
import 'dart:convert';

// 定义应用状态
class AppState {
  final int counter;
  final String username;

  AppState({required this.counter, required this.username});

  AppState copyWith({int? counter, String? username}) {
    return AppState(
      counter: counter ?? this.counter,
      username: username ?? this.username,
    );
  }
}

// 初始状态
final initialState = AppState(counter: 0, username: '');

// 定义action
enum AppAction { increment, decrement, setUsername }

// Action Creator
class IncrementAction {}
class DecrementAction {}
class SetUsernameAction {
  final String username;
  SetUsernameAction(this.username);
}

// Reducer
Reducer<AppState> buildReducer() {
  return combineReducers<AppState>([
    TypedReducer<AppState, IncrementAction>(_increment),
    TypedReducer<AppState, DecrementAction>(_decrement),
    TypedReducer<AppState, SetUsernameAction>(_setUsername),
  ]);
}

AppState _increment(AppState state, IncrementAction action) {
  return state.copyWith(counter: state.counter + 1);
}

AppState _decrement(AppState state, DecrementAction action) {
  return state.copyWith(counter: state.counter - 1);
}

AppState _setUsername(AppState state, SetUsernameAction action) {
  return state.copyWith(username: action.username);
}

3. 配置持久化

配置redux_persist_flutter来持久化你的Redux Store。

import 'package:flutter/material.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux_persist_flutter/redux_persist_flutter.dart';
import 'package:redux_persist/src/storage/flutter_storage.dart';
import 'dart:convert';

void main() {
  final persistConfig = PersistConfig<AppState>(
    storage: FlutterStorage(),
    keyPrefix: 'app_',
    serializer: JsonSerializer<AppState>(
      toJson: (state) => jsonEncode(state.toJson()),
      fromJson: (json) => AppState.fromJson(jsonDecode(json)),
    ),
    blacklist: [], // 如果需要忽略某些字段,可以添加到黑名单中
  );

  final store = Store<AppState>(
    buildReducer(),
    initialState: initialState,
    middleware: [persistMiddleware(config: persistConfig)],
  );

  runApp(
    StoreProvider<AppState>(
      store: store,
      child: MyApp(),
    ),
  );
}

// 示例:将AppState转换为JSON
extension AppStateToJson on AppState {
  Map<String, dynamic> toJson() => {
    'counter': counter,
    'username': username,
  };

  factory AppState.fromJson(Map<String, dynamic> json) => AppState(
        counter: json['counter'] as int,
        username: json['username'] as String,
      );
}

4. 使用Store

在你的应用中,通过StoreProvider访问Redux Store。

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Redux Persist Demo')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Counter: ${storeCounter(context)}'),
              SizedBox(height: 20),
              Text('Username: ${storeUsername(context)}'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () => context.dispatch(IncrementAction()),
                child: Text('Increment'),
              ),
              ElevatedButton(
                onPressed: () => context.dispatch(DecrementAction()),
                child: Text('Decrement'),
              ),
              ElevatedButton(
                onPressed: () => context.dispatch(SetUsernameAction('John Doe')),
                child: Text('Set Username'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Widget storeCounter(BuildContext context) {
  return StoreConnector<AppState, int>(
    converter: (store) => store.state.counter,
    builder: (context, counter) {
      return Text('Counter: $counter');
    },
  );
}

Widget storeUsername(BuildContext context) {
  return StoreConnector<AppState, String>(
    converter: (store) => store.state.username,
    builder: (context, username) {
      return Text('Username: $username');
    },
  );
}

这样,你就完成了在Flutter项目中使用redux_persist_flutter进行持久化状态管理的设置。这个示例代码展示了如何定义状态、action和reducer,如何配置持久化,以及如何在UI组件中访问和修改状态。

回到顶部