Flutter状态管理

Google推荐使用使用provider进行状态管理。
class Counter with ChangeNotifier{
int value=0;

increment(){
value++;
notifyListeners();//它会通知所有听众进行刷新。
}
}

flutter入口文件
void main() {
var counter = Counter();
runApp(ChangeNotifierProvider.value(
value: counter,
child: MyApp(),
),
);
}

//需要额外传递值
void main() {
final counter = Counter();
final text= "hello world";
runApp(
Provider.value(
value: text,
child: ChangeNotifierProvider.value(
value: counter,
child: MyApp(),
),
),
);
}

多个Provider时MultiProvider
void main() {
final counter = Counter();
final counter2 = Counter2();
final text= "hello world";

runApp(
MultiProvider(providers: [
ChangeNotifierProvider.value(
value: counter),
Provider.value(value: text,child:
ChangeNotifierProvider.value(value: counter2))
],child: MyApp())
);
}

获取对象状态
class MyText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 200),
child: Text(Provider.of(context).value.toString()),
);
}
}

class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(onPressed: () {
Provider.of(context).increment();
}, child: Text('递增')),
);
}
}
Button直接回调
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Consumer(builder: (context,Counter counter,child)=>RaisedButton(onPressed: () {
counter.increment();
}, child: Text('递增'))),
);
}
}

你可能感兴趣的:(Flutter状态管理)