Flutter的狀態(tài)管理有:
1、State:Flutter自帶的悉稠,開發(fā)耦合度高宫蛆,不推薦
2艘包、fish_redux:阿里開源的的猛,中型和大型應(yīng)用,實(shí)力有保證
3想虎、provide:Google官方的卦尊,但是很久沒(méi)更新了,官方推薦了provider
4舌厨、provider:InheritedWidget的封裝 岂却,Google推薦,目前更新活躍裙椭。
我們選擇provider開發(fā)我們的應(yīng)用:
provider
Provider 是用于提供數(shù)據(jù)躏哩,無(wú)論是在單個(gè)頁(yè)面還是在整個(gè) app 都有它自己的解決方案,我們可以很方便的管理狀態(tài)揉燃。
下面將演示provider最新版4.1.2
(2020年5月15日
)
4.x 跟3.x有所不同扫尺,具體可https://github.com/rrousselGit/provider
目前網(wǎng)上大多數(shù)是3.x 及其以下的教程
注意
provider 4.x 在 Flutter v1.12.13+hotfix.9 穩(wěn)定版(2020年5月15日
)上是不支持的;
剛好在2020年5月6日出了Flutter 1.17.0 穩(wěn)定版炊汤,是支持 provider 4.x 的正驻,而現(xiàn)在的最新穩(wěn)定版是 Flutter 1.17.1(2020年5月15日
);下面我將使用最新穩(wěn)定版來(lái)開發(fā)抢腐。
環(huán)境
Flutter 1.17.1 + provider 4.1.2(2020年5月15日最新版
)
一姑曙、 引入依賴
pubspec.yaml
dependencies:
provider: ^4.1.2
二、創(chuàng)建狀態(tài)管理
創(chuàng)建 bli/provider/current_index_page.dart
current_index_page.dart
內(nèi)容如下:
import 'package:flutter/material.dart';
/// 當(dāng)前索引頁(yè)
class CurrentIndexPage with ChangeNotifier {
int currentIndexPage = 0;
void changeIndexPage(int newIdex) {
currentIndexPage = newIdex;
notifyListeners(); // 通知所有的監(jiān)聽器
}
}
三迈倍、調(diào)用
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './provider/current_index_page.dart';
void main() {
runApp(
MultiProvider(
providers: [
// 引入
ChangeNotifierProvider(create: (_) => CurrentIndexPage()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
int _index; // 過(guò)渡值
@override
Widget build(BuildContext context) {
// 初始化過(guò)渡值 _index=0
_index = context.watch<CurrentIndexPage>().currentIndexPage;
return new MaterialApp(
title: 'Demo', // 設(shè)置 App 的標(biāo)題
theme: new ThemeData(primaryColor: Colors.blue), // 設(shè)置主題顏色
home: new Scaffold(
body: new Center(
child: new MaterialButton(
color: Colors.blue,
textColor: Colors.white,
child: new Text(
'點(diǎn)我 ${context.watch<CurrentIndexPage>().currentIndexPage}'), //訂閱 取值
onPressed: () {
++_index;
// 傳遞對(duì)象 →→→→ 調(diào)用狀態(tài)管理修改 當(dāng)前索引頁(yè)的值 currentIndexPage=_index
context.read<CurrentIndexPage>().changeIndexPage(_index);
},
)),
),
);
}
}