skip to Main Content

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

2

Answers


  1. you can use Consumer/Selector, Their optional child argument allows rebuilding only a particular part of the widget tree:

    Foo(
        child: Consumer<A>(
          builder: (_, a, child) {
            return Bar(a: a, child: child);
          },
          child: Baz(),
        ),
      )
    
    Login or Signup to reply.
  2. 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>();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search