Flutter-MultiProvider如何与相同类型的提供者一起工作? [英] Flutter - How does MultiProvider work with providers of the same type?

查看:86
本文介绍了Flutter-MultiProvider如何与相同类型的提供者一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我试图一次获取多个流发出的数据,但是其中两个或多个流发出相同类型的数据,比方说一个字符串.

For example, I am trying to obtain data emitted for multiple streams at once, but 2 or more of these streams emit data of the same type, lets say a string.

我的问题是,是否仍然可以使用相同类型的 MultiProvider 和多个 StreamProvider (或任何提供程序,但我对这种情况感兴趣)能够访问他们每个人发出的数据?

My question is, is it possible to use MultiProvider and use multiple StreamProvider (or any provider, but I am interested in this case) of the same type while still being able to access the data emitted by each one of them?

对此的一种解决方案是在使用常见数据类型时使用 StreamBuilder ,但我真的很喜欢 MultiProvider 在更简洁的代码方面提供的功能.

A solution for this is using a StreamBuilder when using common data types but I really like what the MultiProvider offers in terms of cleaner code.

示例:

class MyScreen extends StatelessWidget {
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<String>(stream: Observable.just("stream1")),
        StreamProvider<String>(stream: Observable.just("stream2")),
        StreamProvider<String>(stream: Observable.just("stream3"))
      ],
      child: Builder(
        builder: (BuildContext context) {
          AsyncSnapshot<String> snapshot =
              Provider.of<AsyncSnapshot<String>>(context);
          String data = snapshot.data;
          return Text(data); 
        },
      ),
    );
  }
}

推荐答案

MultiProvider 还是不改变任何东西.如果两个提供程序共享同一类型,则最深的一个将覆盖该值.

MultiProvider or not doesn't change anything. If two providers share the same type, the deepest one overrides the value.

不可能从不是给定类型的最接近祖先的提供者那里获取值.

It's not possible to obtain the value from a provider that is not the closest ancestor for a given type.

如果您需要独立访问所有这些值,则每个值都应具有唯一的类型.

If you need to access all of these values independently, each should have a unique type.

例如,代替:

Provider<int>(
  value: 42,
  child: Provider<int>(
    value: 84,
    child: <something>
  ),
)

您可以这样做:

class Root {
  Root(this.value);

  final int value;
}

class Leaf {
  Leaf(this.value);

  final int value;
}


Provider<Root>(
  value: Root(42),
  child: Provider<Leaf>(
    value: Leaf(84),
    child: <something>
  ),
)

这允许使用以下方法独立获取每个值:

This allows to obtain each value independently using:

Provider.of<Root>(context)
Provider.of<Leaf>(context);

这篇关于Flutter-MultiProvider如何与相同类型的提供者一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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