skip to Main Content

I am learning how to use RiverPod to handle state management in Flutter.

I have some confuse when create a global instance of a provider.

   final counterProvider = StateNotifierProvider<Counter, int>((ref) {
      return Counter();
    });

    class Counter extends StateNotifier<int> {
      Counter() : super(0);
      void increment() => state++;
    }

Above is an example.

When I created an instance of counterProvider, so it is a global instance.

So if my app has a lot of instances for a lot of functions.

Have it have a bad affect to performance like time to start an app,…?

If the functions are not used by the user most of the time using the application, is it a waste of resources?

2

Answers


  1. Chosen as BEST ANSWER

    I have read an article about riverpod lifecycle in https://codewithandrea.com/articles/flutter-riverpod-data-caching-providers-lifecycle/

    And I got that: The global instance does not store or init anything about state when it declares.

    State of provider just init when it call inside ref.watch(...)

    And its state can be cleared when we set keepAlive = false or declare the provider with autoDispose.


  2. No, it will not be a waste of resources. There is an autoDispose method which you can use to dispose off the provider when it’s not in use.

    Riverpod is generally meant to be used via global variables which are your providers. Also, it is better when it comes to performance as you are only redrawing / updating a specific part of your UI and not the whole screen (like in setState).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search