Provider共享数据的两种方式 方式一:
Provider.of<CountViewModel>(context);
举例
import 'package:flutter/material.dart';
class CountViewModel extends ChangeNotifier{
int _count = 0;
int get count=>_count;
addCount(){
_count++;
notifyListeners();
}
deCount(){
_count--;
notifyListeners();
}
}
import 'package:flutter/material.dart';
import 'package:navigatoritem/page/CountViewModel.dart';
import 'package:provider/provider.dart';
class B extends StatefulWidget{
_BState createState() =>_BState();
}
class _BState extends State<B>{
@override
Widget build(BuildContext context){
final counter = Provider.of<CountViewModel>(context);
return Scaffold(
appBar:AppBar(
title: Text("计数器"),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
Provider.of<CountViewModel>(context,listen: false).addCount();
},
),
body: Container(
child: Center(
child: Text("${counter.count}"),
),
),
);
}
}
Provider.of(context) 会导致调用的 context 页面范围的刷新。 Consumer 只刷新了 Consumer 的部分 建议尽量使用 Consumer 而不是 Provider.of(context) 获取顶层数据
方式二
import 'package:flutter/material.dart';
import 'package:navigatoritem/page/CountViewModel.dart';
import 'package:provider/provider.dart';
class B extends StatefulWidget{
_BState createState() =>_BState();
}
class _BState extends State<B>{
@override
Widget build(BuildContext context){
final counter = Provider.of<CountViewModel>(context);
return Consumer(
builder: (context,CountViewModel counter,_){
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
counter.addCount();
},
),
appBar: AppBar(
title: Text("Consumer数据共享"),
),
body: Text("${counter.count}"),
);
},
);
}
}
|