状态:即数据;全局状态:即很多页面或组件要共用的数据。
Flutter官方将状态分为:短时 (ephemeral) 状态和应用 (app) 状态。所谓短时 (ephemeral) 状态即widget(组件)自己使用的数据;应用状态即本文所说的全局状态。
无论学习任何框架(vuex、redux)中的状态管理,其的核心还是在于如何存储数据以及如何获取到存储的数据,Provider是Flutter官方推荐的全局状态管理库。
接下来我们通过Provider官方示例来说明如何在应用中使用Provider管理全局数据。
一、全局状态管理类
全局混入的ChangeNotifier ,ChangeNotifier 是 Flutter SDK 中的一个简单的类。用于向监听器发送通知。换言之,如果被定义为 ChangeNotifier ,你可以订阅它的状态变化。
对于特别简单的程序,可以通过一个 ChangeNotifier 来满足全部需求。在相对复杂的应用中,由于会有多个模型,所以可能会有多个 ChangeNotifier 。
全局混入的DiagnosticableTreeMixin,可以帮助在devtools中进行更好地调试。
import 'package:flutter/foundation.dart';
/// Mix-in [DiagnosticableTreeMixin] to have access to [debugFillProperties] for thdevtool
// ignore: prefer_mixin
class Counter with ChangeNotifier, DiagnosticableTreeMixin {
// 定义数据
int _count = 0;
// 向外暴露_count的值
int get count => _count;
// 修改数据
void increment() {
_count++;
notifyListeners(); // 更新UI视图
}
/// 为了方便调试devtools
/// Makes `Counter` readable inside the devtools by listing all of its properties
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('count', count));
}
}
唯一一行和 ChangeNotifier 相关的代码就是调用 notifyListeners() 。当数据发生改变并且需要更新 UI 的时候可以调用该方法。而剩下的代码就是 Counter 和它本身的业务逻辑。
二、全局注入
ChangeNotifierProvider widget 可以向其子孙节点暴露一个 ChangeNotifier 实例。
/// This is a reimplementation of the default Flutter application using provider + [ChangeNotifier].
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
如果想提供多个状态,需要使用 MultiProvider :
/// This is a reimplementation of the default Flutter application using provider + [ChangeNotifier].
void main() {
runApp(
/// Providers are above [MyApp] instead of inside it, so that tests
/// can use [MyApp] while mocking the providers
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
三、使用全局状态
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text('You have pushed the button this many times:'),
/// Extracted as a separate widget for performance optimization.
/// As a separate widget, it will rebuild independently from [MyHomePage].
///
/// This is totally optional (and rarely needed).
/// Similarly, we could also use [Consumer] or [Selector].
Count(),
],
),
),
floatingActionButton: FloatingActionButton(
key: const Key('increment_floatingActionButton'),
/// Calls `context.read` instead of `context.watch` so that it does not rebuild
/// when [Counter] changes.
onPressed: () => context.read<Counter>().increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<Counter>().count}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headline4);
}
}
Provider官方相关文档内容:
简单的应用状态管理 | Flutter 中文文档 | Flutter 中文开发者网站
provider | Flutter Package
往期内容:
一、【Flutter开发环境搭建】Java SDK安装
二、【Flutter开发环境搭建】Android SDK、Dart SDK及Flutter SDK安装_
三、Flutter Navigator路由传参
|