[Detailed] Flutter's Global State Management Provider
@author
As.Kai
First import dependencies
provide: ^1.0.2
The latest version can be viewed on the pub
After importing, create a state management Provide under the lib folder:
Official website example:
Create a static page data management++ Demo
eg:
Create a counter.dart file in the provide folder:
import 'package:flutter/cupertino.dart';
class Counter with ChangeNotifier{
int value = 0;
increment(){
value++;
//内部方法 用户每次调用value++方法 会通知我们执行了该方法
//局部刷新Widget
notifyListeners();
}
}
Note that the notifyListeners(); method means monitoring and partial refreshing. After
writing the ++ method, you must write the dependency in main.dart:
void main(){
//连接状态管理器
var counter = new Counter();
var providers = new Providers();
//依赖 (规范) 如果有多个管理器 分号在最后一个管理器结束
//改泛型和管理器名称
providers..provide(
Provider<Counter>.value(counter)
);
//多管理器配置(多管理器除最后一个分号结束,其他不需要分号)
// ..provide(Provider<Counter>.value(counter));
// ..provide(Provider<Counter>.value(counter));
runApp(
ProviderNode(
child: MyApp(),providers: providers,
)
);
}
Pay attention to the configuration of runApp(), many people will forget this step of configuration and cause the program to report an error
Write a text and a button on the layout page, click the button text number plus 1
reference method: the
text needs to be wrapped with the Provide control <generic manager name> {There is a constructor build(
3 parameters (context, subclass child, controller counter)) { Directly return a control eg: return new Text('${counter.value}'); OK } }
Code:
class Number extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
//需要包裹一层Provide<Counter>泛型
child: new Provide<Counter>(
//构造器
builder: (context,child,counter){
return new Text('${counter.value}');
},
),
);
}
}
At the button:
Click the event to call the ++ method in the manager.
Call the method:
Provide.value<generic manager class Counter>(context).increment();
Code:
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new RaisedButton(
//点击事件
onPressed: () {
//通过Provide.value<>泛型的方式获取上下文后
// 使用我们创建的increment value++方法
Provide.value<Counter>(context).increment();
},
child: new Text('状态管理点击递增'),
);
}
}
A simple Provide is complete. Flutter run. Let's see the effect!
Follow me and grow together!
-As.Kai