Flutter 中使用Provide状态管理
2019-08-16 本文已影响0人
NightRainBreeze
关于Provide
pubspec
dependencies:
provide: ^1.0.2
具体使用
- 创建
/// ChangeNotifier
import 'package:flutter/material.dart’;
/// Provide
import 'package:provide/provide.dart’;
class HomePageCarProvide with ChangeNotifier {
int _value = 0;
int get value => _value;
HomePageCarProvide(this._value);
void increment() {
_value++;
notifyListeners();
}
void decrement() {
_value—;
notifyListeners();
}
}
- 初始化
void main() {
final providers = Providers()
..provide(Provider.function((context) => HomePageCarProvide(0)));
runApp(ProviderNode(
providers: providers,
child: CounterApp(),
));
}
- 接收方 Provide<HomePageCarProvide>(builder: (context, child, provide){})
class MyText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Provide<HomePageCarProvide>(builder: (context, child, provide) {
return Text("${provide.value}”);
}),
);
}
}
- 发送方 Provide.value<HomePageCarProvide>(context)
class MyBtn extends StatelessWidget {
@override
Widget build(BuildContext context) {
final p = Provide.value<HomePageCarProvide>(context);
return Container(
child: RaisedButton(
onPressed: () {
p.increment();
},
child: Text("+”),
),
);
}
}