内容简介:Provider 是 Google I/O 2019 大会上宣布的现在官方推荐的状态管理方式,而 ChangeNotifierProvider 可以说是 Provider 的一种。Provider GitHub 地址:再贴一个油管上的视频:
Provider 是 Google I/O 2019 大会上宣布的现在官方推荐的状态管理方式,而 ChangeNotifierProvider 可以说是 Provider 的一种。
Provider GitHub 地址: github.com/rrousselGit…
再贴一个油管上的视频: www.youtube.com/watch?v=xcS…
OK,那废话不多说。下面具体看看如何使用 ChangeNotifierProvider 做状态管理。
通过一个 demo 来展示 ChangeNotifierProvider 的使用。该 demo 实现的功能很简单,计数 + 切换主题。仅有两个页面,两个页面共享相同的数据。
效果图:
我已经将这个小 demo 上传至 GitHub: github.com/MzoneCL/flu…
第一步: 添加依赖
在 pubspec.yaml 文件中添加依赖。
provider 包 pub 地址:pub.dev/packages/pr…
第二步:创建共享数据类
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class DataInfo with ChangeNotifier {
int _count = 0;
ThemeData _themeData = ThemeData.light();
get count => _count;
get themeData => _themeData;
addCount() {
_count++;
notifyListeners();
}
subCount() {
_count--;
notifyListeners();
}
changeTheme() {
if (_themeData == ThemeData.light()) {
_themeData = ThemeData.dark();
} else {
_themeData = ThemeData.light();
}
notifyListeners();
}
}
复制代码
数据类需要 with ChangeNotifier 以使用 notifyListeners() 函数通知监听者以更新界面。
第三步:获取数据
Provider 获取数据状态有两种方式:
- 使用 Provider.of(context) 获取 DataInfo
- 使用 Consumer
不过这两种方式都需要在顶层套上ChangeNotifierProvider():
1. 使用 Provider.of(context) 获取 DataInfo
例如,指定主题部分的代码如下:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var dataInfo = Provider.of<DataInfo>(context);
return MaterialApp(
home: MyHomePage(),
theme: dataInfo.themeData,
);
}
}
复制代码
通过Provider.of<DataInfo>(context) 获取 DataInfo 实例,需要在 of 函数后指明具体的数据类。然后就可以直接通过 getter 访问到 themeData 了。
2.使用 Consumer
同样,以指定主题部分代码为例:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<DataInfo>(
builder: (context, dataInfo, _) => MaterialApp(
home: MyHomePage(),
theme: dataInfo.themeData,
),
);
}
}
复制代码
直接用 Consumer 包住需要使用共享数据的 Widget,同样的,Consumer 也要指明类型。
OK,以上就是 ChangeNotifierProvider 的基本使用了。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 前端状态管理与有限状态机
- 为管理复杂组件状态困扰?试试 vue 简单状态管理 Store 模式
- 基于有限状态机的广告状态管理方案及实现
- 基于有限状态机的广告状态管理方案及实现
- vue状态管理演进
- 浅析前端状态管理
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First jQuery
Ryan Benedetti , Ronan Cranley / O'Reilly Media / 2011-9 / USD 39.99
Want to add more interactivity and polish to your websites? Discover how jQuery can help you build complex scripting functionality in just a few lines of code. With Head First jQuery, you'll quickly g......一起来看看 《Head First jQuery》 这本书的介绍吧!