Search code examples
flutterprovider

Provider update all Widget


I’m using Provider in my app and my ask/issues is:

I have 2 Pages which use a provider. In this Provider has a variable String which show in one page but the another Page change the value of this variable. So, when change the value of variable my Page Update all Widget (From scaffold) instead of widget which use the variable

I use the provider with provider.of before the Return of the build


Solution

  • Provider.of also has another parameter called listen.Its default value is true.

      /// Obtains the nearest [Provider<T>] up its widget tree and returns its
      /// value.
      ///
      /// If [listen] is `true`, later value changes will trigger a new
      /// [State.build] to widgets, and [State.didChangeDependencies] for
      /// [StatefulWidget].
      ///
      /// `listen: false` is necessary to be able to call `Provider.of` inside
      /// [State.initState] or the `create` method of providers like so:
      ///
      /// ```dart
      /// Provider(
      ///   create: (context) {
      ///     return Model(Provider.of<Something>(context, listen: false)),
      ///   },
      /// )
      /// ```
      static T of<T>(BuildContext context, {bool listen = true})
    

    If listen is true, then when the value of provider changes, the state will be rebuilt. You can use listen: false to get the Provider and wrap the widget you want to update with Selector or Consumer.

    Provider has added extensions to BuildContext, allowing you to use watch or read for a more intuitive way of accessing Provider.

      T read<T>() {
        return Provider.of<T>(this, listen: false);
      }
    
      T watch<T>() {
        return Provider.of<T>(this);
      }
    
      context.watch<XX>();
      context.read<XX>();