如何在Flutter中以相同类型添加多个ChangeNotifierProvider [英] how to add multiple ChangeNotifierProvider in same type in Flutter

查看:289
本文介绍了如何在Flutter中以相同类型添加多个ChangeNotifierProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将相同类型的多个ChangeNotifierProvider添加?

Is it possible to add same type multiple ChangeNotifierProvider?

return MultiProvider(
  providers: [
      ChangeNotifierProvider<ValueNotifier<double>>(
        create: (_) => ValueNotifier<double>(0.0),
      ),
      ChangeNotifierProvider<ValueNotifier<double>>(
        create: (_) => ValueNotifier<double>(0.0),
      ),
  ],

在我的构建方法中

 @override
  Widget build(BuildContext context) {
    ValueNotifier<double> firstNotifier = Provider.of(context, listen: true);
    ValueNotifier<double> secondNotifier = Provider.of(context, listen: true);

  print('First value ${firstNotifier.value} Second value ${secondNotifier.value}');

 ...
 onTap:(){
   firstNotifier.value = 10.0;
   secondNotifier.value = 30.0;
 }

两个打印的值都相同第一个值为10第二个值为10

推荐答案

这样做是不可能的.您必须提供不同类型的提供程序才能获得正确的价值.

It is impossible to do so. You have to provide different types of provider to get correct value.

如果您多次使用同一提供者,那么它将为您提供小部件树中最近的提供者值.

If you use same provider more than once then it will give you value of nearest provider value in widget tree.

在他们的官方文档中也有提及.

It is also mention in their official documentation.

在这里签出.我可以使用同一类型获得两个不同的提供者吗?

这篇关于如何在Flutter中以相同类型添加多个ChangeNotifierProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆