🍎 多数据共享使用MultiProvider,在providers中定义所有的共享数据:
main() {
runApp(MultiProvider(
providers: providers,
child: DBJMyApp(),
));
}
List<SingleChildWidget> providers = [
ChangeNotifierProvider(create: (cxt) => DBJHomeViewModel(290)), //共享数据1
ChangeNotifierProvider(
create: (cxt) => DBJUserViewModel(
DBJUserModel(nickName: 'jack', age: 12, sex: 'male'), //共享数据2
),
),
];
🍎 Widget中使用共享数据:
class DBJUserInfo extends StatelessWidget {
const DBJUserInfo({Key? key}) : super(key: key);
/// Consumer2获取共享数据
@override
Widget build(BuildContext context) {
return Consumer2<DBJHomeViewModel, DBJUserViewModel>(
builder: (cxt, homeViewModel, userViewModel, child) {
String? nickName = userViewModel.model.nickName;
String? sex = userViewModel.model.sex;
int? age = userViewModel.model.age;
return Column(
children: [
Text(
'数量信息:${homeViewModel.counter}',
style: TextStyle(fontSize: 15, color: Colors.red),
),
Text(
'用户信息:$nickName $sex $age',
style: TextStyle(fontSize: 15, color: Colors.blue),
),
],
);
},
);
}
}
网友评论