1.在pubspec.yaml中添加Provide的依赖
provide: ^1.0.2
2.创建provide
混入了ChangeNotifier,意思是可以不用管理听众。现在你可以看到数和操作数据的方法都在Provide中,很清晰的把业务分离出来了。通过notifyListeners可以通知听众刷新。
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int value = 0;
increment() {
value++;
notifyListeners();//通知听众值改变了,局部刷新界面
}
}
3.将状态放入顶层
先引入provide和counter:
import 'package:provide/provide.dart';
import './provide/counter.dart';
然后进行将provide和counter引入程序顶层。
void main() {
//provider顶层依赖
var counter = Counter();
var providers = Providers();
providers..provide(Provider<Counter>.value(counter));
runApp(ProviderNode(
child: MyApp(),
providers: providers,
));
}
}
4.获取和修改provide状态
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>[
Number(),
MyButton(),
],
),
),
);
}
}
class Number extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 200.0),
child: Provide<Counter>(
//状态管理获取值
builder: (context, child, counter) {
return Text(
'${counter.value}',
style: Theme.of(context).textTheme.display1,
);
},
),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
//状态管理修改状态
onPressed: () {
Provide.value<Counter>(context).increment();
},
child: Text('递增'),
),
);
}
}