Flutter状态持久化插件hydrated_state_notifier的使用

Flutter状态持久化插件hydrated_state_notifier的使用

hydrated_state_notifier 是一个扩展了 state_notifier 库的功能,能够自动持久化和恢复状态的插件。它依赖于 HydratedStorage 来实现数据存储,通常与 hive 数据库结合使用。

Features 特性

  • 自动持久化和恢复状态。
  • 支持通过自定义 HydratedStorage 实现来扩展功能。
  • 提供了对不同实例的状态管理支持。

Usage 使用方法

Setup HydratedStorage 设置

Install 安装

首先,在项目中添加 hydrated_state_notifierhydrated_state_notifier_hive 包:

dart pub add hydrated_state_notifier hydrated_state_notifier_hive

Import package 导入包

在Dart文件中添加以下导入语句:

import 'package:hydrated_state_notifier/hydrated_state_notifier.dart';
import 'package:hydrated_state_notifier_hive/hydrated_state_notifier_hive.dart';

Initialize 初始化

在应用启动时初始化 HydratedStorage

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化存储
  HydratedStorage.storage = await HiveHydratedStorage.build(
    storageDirectory: kIsWeb
        ? ''
        : await getTemporaryDirectory(),
  );

  runApp(App());
}

Create a HydratedStateNotifier 创建HydratedStateNotifier

下面是一个简单的计数器控制器的例子:

class CounterController extends HydratedStateNotifier<int> {
  CounterController() : super(0);

  void increment() => state = state + 1;

  [@override](/user/override)
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  [@override](/user/override)
  Map<String, int> toJson(int state) => { 'value': state };
}

这样,CounterController 就会自动保存和恢复其状态了。

如果需要为同一类型的多个实例创建不同的缓存,可以使用 id 参数:

final counterOne = CounterController('counter_1');
final counterTwo = CounterController('counter_2');

Complete Example 完整示例

这里提供了一个完整的示例,包括设置存储、创建控制器以及如何在Flutter应用中使用它们。

import 'package:flutter/material.dart';
import 'package:hydrated_state_notifier/hydrated_state_notifier.dart';
import 'package:hydrated_state_notifier_hive/hydrated_state_notifier_hive.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化存储
  HydratedStorage.storage = await HiveHydratedStorage.build(
    storageDirectory: await getApplicationDocumentsDirectory(),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Hydrated State Notifier Demo')),
        body: Center(child: CounterWidget()),
      ),
    );
  }
}

class CounterWidget extends StatefulWidget {
  [@override](/user/override)
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  final CounterController _counterController = CounterController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return ValueListenableBuilder<int>(
      valueListenable: _counterController,
      builder: (context, count, _) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Text('$count', style: Theme.of(context).textTheme.headline4),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _counterController.increment(),
              child: Text('Increment'),
            ),
          ],
        );
      },
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用hydrated_state_notifier插件来实现状态持久化的代码示例。hydrated_state_notifier是一个扩展自state_notifier的库,它允许你轻松地将应用状态持久化到本地存储(如SharedPreferences)。

首先,确保你已经在pubspec.yaml文件中添加了必要的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_hooks: ^0.18.0 # 如果你使用hooks
  provider: ^6.0.0
  state_notifier: ^0.7.0
  hydrated_bloc: ^8.0.0 # hydrated_state_notifier是hydrated_bloc的一部分
  shared_preferences: ^2.0.13 # 用于本地存储

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

接下来,我们将创建一个简单的示例,展示如何使用hydrated_state_notifier来持久化计数器状态。

  1. 定义计数器状态
import 'package:state_notifier/state_notifier.dart';

class CounterState {
  final int value;

  CounterState(this.value);

  // 为了方便比较状态,可以重写==和hashCode方法
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is CounterState && runtimeType == other.runtimeType && value == other.value;

  @override
  int get hashCode => value.hashCode;
}
  1. 创建状态通知器
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:state_notifier/state_notifier.dart';

class CounterNotifier extends HydratedStateNotifier<CounterState> {
  CounterNotifier() : super(CounterState(0)) {
    // 在构造函数中恢复状态
    restoreState();
  }

  void increment() {
    state = CounterState(state.value + 1);
  }

  @override
  CounterState? fromJson(Map<String, dynamic> json) {
    return json['value'] != null ? CounterState(json['value'] as int) : null;
  }

  @override
  Map<String, dynamic> toJson(CounterState state) {
    return {'value': state.value};
  }
}
  1. 设置存储

main.dart中,设置HydratedBlocDelegateSharedPreferences

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'counter_notifier.dart'; // 假设你的CounterNotifier在这里

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final SharedPreferences preferences = await SharedPreferences.getInstance();
  runApp(
    MultiProvider(
      providers: [
        StateNotifierProvider<CounterNotifier>(
          create: (_) => CounterNotifier(),
        ),
      ],
      child: HydratedBlocProvider(
        storage: SharedPreferencesStorage(preferences),
        child: MyApp(),
      ),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Hydrated State Notifier Demo')),
        body: Center(
          child: CounterScreen(),
        ),
      ),
    );
  }
}
  1. 创建UI
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'counter_notifier.dart'; // 假设你的CounterNotifier在这里

class CounterScreen extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final counterNotifier = context.read<CounterNotifier>();

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('You have pushed the button this many times:'),
        Text(
          '${counterNotifier.state.value}',
          style: Theme.of(context).textTheme.headline4,
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () {
            counterNotifier.increment();
          },
          child: Text('Increment'),
        ),
      ],
    );
  }
}

这个示例展示了如何使用hydrated_state_notifier来创建一个简单的计数器应用,并将其状态持久化到SharedPreferences中。当你重新启动应用时,计数器的值将会被恢复。

回到顶部