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

后端 未结 1 694
离开以前
离开以前 2021-02-06 01:57

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 i

相关标签:
1条回答
  • 2021-02-06 02:43

    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);
    
    0 讨论(0)
提交回复
热议问题