flutter的状态管理有多种类,复杂程度,学习难度都不一样,最基本的要属于Stateful及其setState方法,但是数据变化时刷新绘制页面,资源有点浪费,其实我们只想要重绘某个变化的Widget即可,如Text()的文本变化,只要重绘Text就行,没有必要全部重绘,对于大型app显得更为重要.因此出现了多种状态管理的所谓框架
这里介绍Provider的基本使用,可以用在程序入口级别的,就是把Provider包裹在MaterialApp的上面,如管理app的主题色或语言等,可以控制MaterialApp的数据变化,而普通的数据没有必要放在程序入口开始监控,这样会浪费资源,普通的状态管理只要在页面级别就可以.也就是把Provider包裹在Scaffold上面即可实施状态管理.
依赖库 provider: ^4.0.2
导入类 import ‘package:provider/provider.dart’;
MultiProvider({
Key key,
List providers,
Widget child})
ChangeNotifierProvider ChangeNotifierProvider( //Counter是举例的类,T代替
{Key key},
{Counter Function(BuildContext) create},
{bool lazy},
{Widget child})
举例ChangeNotifierProvider(create: (_) => Counter()),
Consumer Consumer( //Counter是例子中的类
{Key key},
{Widget Function(BuildContext, Counter, Widget) builder},
{Widget child})
class Counter with ChangeNotifier { //with类型的类ChangNotifier
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners(); }} //通知监听
利用ChangeNotifierProvider来包裹Scaffold
class _MyHomeState extends State {
//Counter _counter = new Counter();
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider( //ChangeNotifierProvider单个监控用来,而MultiProvider放置多个监控
create: (_) => Counter(), //绑定数据
child: Scaffold(...)}
在放置监控同时绑定数据,这个数据分离的易于管理
class _MyHomeState extends State {
//Counter _counter = new Counter();
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider( //ChangeNotifierProvider单个监控用来,而MultiProvider放置多个监控
create: (_) => Counter(), //绑定数据
child: Scaffold(...)}
和程序入口级别的差异
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
Color _themeColor;
return MultiProvider( //多个监控用MultiProvider
providers: [ChangeNotifierProvider(create: (_) => Counter())], //放置监控
child: Consumer( // 数据展示,有变化会刷新MaterialApp()
builder: (BuildContext context, Counter counter, Widget child) {
_themeColor = counter.themeColor;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: _themeColor,
),
home: MyHome(),
);
}),
);
}
}
用Consumer来监控单个Widget,节省资源
Consumer( //像组件一样使用,因为返回的是Widget
builder: (BuildContext context, Counter counter, Widget child) {
return Text("通过consumer获取的值:${counter.value}"); }, ),
也可以用Provider.of来展示数据
Text(“用Provider.of获取值:${Provider.of(context).value}”)
注意点,如果是在包含Scaffold的类里不能用Provider.of
解决方法用Build方法来包裹Scaffold
child: Builder(
builder: (BuildContext context){
return Scaffold(...)
解决方法或者包裹需要展示数据的那个Widget
Builder( builder: (BuildContext context){
return Text("用Build返回后利用Provider.of获取值:${Provider.of(context).value}");})
添加依赖 provider: ^4.0.2 到新建的工程里,下面代码复制到main.dar(清除原来的代码)即可,标题栏里没有用consumer包裹,所以不会自动,只有热重载能变化,主要是用来区别的.
下面的代码已经执行过没有问题,注意第一次比较慢,请耐心等待执行完…
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
SystemUiOverlayStyle systemUiOverlayStyle =
SystemUiOverlayStyle(statusBarColor: Colors.transparent);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
class Counter with ChangeNotifier {
int _count = 1;
Color _themeColor = Colors.blue;
int get value => _count;
Color get themeColor => _themeColor;
void addValue() {
_count++;
notifyListeners();
}
Color changeThemeColor() {
_themeColor = Colors.green;
notifyListeners();
return _themeColor;
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHome(),
);
}
}
class MyHome extends StatefulWidget {
@override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State {
//Counter _counter = new Counter();
@override
Widget build(BuildContext context) {
print('页面重绘了。。。。。。。。。。。');
return ChangeNotifierProvider(
create: (_) => Counter(),
child: Builder(builder: (BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(30),
child: AppBar(
title: Text(
"Provider页面级别的演示:${Provider.of(context).value}"),
),
),
body: Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Consumer(builder:
(BuildContext context, Counter icounter, Widget child) {
return Text(
"Consumer包裹的文本+${icounter.value}", //没有用consumer包裹的不会自动更新,只有页面重绘时才被更新
style: TextStyle(fontSize: 20),
);
}),
SizedBox(
height: 10,
),
Consumer(
builder:
(BuildContext context, Counter counter, Widget child) {
return RaisedButton(
child: Icon(Icons.add),
onPressed: counter.addValue,
);
},
),
SizedBox(
height: 10,
),
DataWidget(), //抽离后的数据展示
],
),
),
);
}),
);
}
}
class DataWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("局部重绘");
return Container(
width: double.infinity,
color: Colors.green[100],
margin: EdgeInsets.all(10),
child: Column(
children: [
Consumer(
builder: (BuildContext context, Counter counter, Widget child) {
return InkWell(
child: Text("抽离后的Widget,并用consumer获取值:${counter.value}"),
onTap: () => counter.addValue(),
);
},
),
SizedBox(
height: 10,
),
ActionChip(
label: Text(
"抽离后用Provider.of获取值:${Provider.of(context).value}"),
onPressed: Provider.of(context).addValue),
],
),
);
}
}