美文网首页
状态管理-MultiProvider

状态管理-MultiProvider

作者: Jean_Lina | 来源:发表于2021-11-24 15:35 被阅读0次

    🍎 多数据共享使用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),
                ),
              ],
            );
          },
        );
      }
    }
    
    

    相关文章

      网友评论

          本文标题:状态管理-MultiProvider

          本文链接:https://www.haomeiwen.com/subject/kvwntrtx.html