I wanted to have an explanation of the difference between Provider package(with usage of ChangeNotifier and ChangeNotifierProvider) and Scoped Model package in Flutter.

After looking at these two methods of managing the state of the application, I was lost because I didn't find any substantial differences in the approach to code writing.

Scoped Model package usage:

class CounterModelWithScopedModel extends Model {
  int _counter = 0;
  int get counter => _counter;

  void increment() {
    _counter++;
    notifyListeners();
  }
}

class CounterAppWithScopedModel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new ScopedModel<CounterModelWithScopedModel>(
      model: new CounterModelWithScopedModel(),
      child: new Column(children: [
        new ScopedModelDescendant<CounterModelWithScopedModel>(
          builder: (context, child, model) => new Text('${model.counter}'),
        ),
        new Text("Another widget that doesn't require scoped model")
      ])
    );
  }
}

Provider package usage:

class CounterModelWithChangeNotifierProvider extends ChangeNotifier {
  int _counter = 0;
  int get counter => _counter;

  void increment() {
    _counter++;
    notifyListeners();
  }
}

class CounterAppWithChangeNotifierProvider extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new ChangeNotifierProvider(
      builder: (context) => CounterModelWithChangeNotifierProvider(),
      child: new Column(children: [
        new Consumer<CounterModelWithChangeNotifierProvider>(
          builder: (context, model, child) => new Text('${model.counter}')
        ),
        new Text("Another widget that doesn't require consume")
      ])
    );
  }
}

Now assume that we have another widget that trigger the notification with increment(); of CounterModelWithChangeNotifierProvider and CounterAppWithScopedModel and cause the widgets to be rebuilt.

I have approached flutter recently and I am quite confused about the management of the application state, I started with Notifier but after seeing that there are an infinite number of ways for do that I do not know what to do. What do you recommend?


Solution 1: Rémi Rousselet

TD;DR:

provider is not scoped_model but can be used to mimic a scoped_model architecture.


scoped_model is an architecture, based on a subclass of Listenable: Model, that is now built-in Flutter under the name of ChangeNotifier

provider is not an architecture, but instead a mean to pass state and manage it. It can be used to make a scoped_model-like architecture, but it can do something else too.


Solution 2: Rudresh Narwal

Provider is a complete dependency injection solution, with some very powerful provider types that take care of boilerplate things like managing streams for instance. Whereas ScopedModel provides the same functionality in terms of reactivity using the Model class + notifyListeners().