Provide是Google官方推出的状态管理模式。官方地址为:https://github.com/google/flutter-provide
下面通过使用Provide来实现如下效果
1、Provide引入项目
provide: ^1.0.2
2、创建Provide
通过notifyListeners可以通知监听者刷新。
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int value =0 ;
//数字+1
increment(){
value++;
notifyListeners();
}
}
3、页面编写
import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import '../provide/counter.dart';
class CartPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
MyNumber(),
MyButton()
],
)
),
);
}
}
class MyNumber extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 200),
//获取数字值
child: Provide<Counter>(
builder: (context, child, counter) {
return Text('${counter.value}', style: TextStyle(fontSize: 30),);
}
),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
onPressed: (){
//修改数字值
Provide.value<Counter>(context).increment();
},
child: Text('递增'),
),
);
}
}
4、修改main.dart
新添加
import 'package:provide/provide.dart';
import './provide/counter.dart';
void main(){
var counter = Counter();
var provides = Providers();
provides..provide(Provider<Counter>.value(counter));
runApp(ProviderNode(child: MyApp(), providers: provides));
}
网友评论