Flutter - How does MultiProvider work with providers of the same type?

帅比萌擦擦* 提交于 2021-02-06 09:10:29

问题


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.

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?

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.

Example:

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); 
        },
      ),
    );
  }
}

回答1:


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.

For example, instead of:

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

You can do:

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);


来源:https://stackoverflow.com/questions/56505413/flutter-how-does-multiprovider-work-with-providers-of-the-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!