创建多个全局实例对性能有不良影响。

huangapple go评论63阅读模式
英文:

Create multi global instances have a bad effect to performance

问题

我正在学习如何在Flutter中使用RiverPod来处理状态管理。

在创建一个Provider的全局实例时,我有一些疑惑。

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

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

上面是一个示例。

当我创建一个counterProvider的实例时,它是一个全局实例。

那么,如果我的应用程序有很多函数的实例,会对性能产生不良影响,比如启动应用程序所需的时间吗?

如果这些函数在大多数时间内用户不使用应用程序,是否会浪费资源?

英文:

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&lt;Counter, int&gt;((ref) {
      return Counter();
    });

    class Counter extends StateNotifier&lt;int&gt; {
      Counter() : super(0);
      void increment() =&gt; 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?

答案1

得分: 1

我阅读了一篇关于Riverpod生命周期的文章,链接:https://codewithandrea.com/articles/flutter-riverpod-data-caching-providers-lifecycle/

我了解到:
全局实例在声明时不存储或初始化与状态有关的任何内容。

Provider的状态只有在ref.watch(...)内调用时才会初始化。

当我们设置keepAlive = false或使用autoDispose声明提供程序时,其状态可以被清除。

英文:

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

得分: 0

不,这不会浪费资源。有一个 autoDispose 方法,您可以使用它来在提供者不再使用时进行处理。

Riverpod 通常通过全局变量来使用,这些全局变量就是您的提供者。而且,从性能方面来说更好,因为您只会重新绘制/更新界面的特定部分,而不是整个屏幕(就像在 setState 中一样)。

英文:

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).

huangapple
  • 本文由 发表于 2023年6月12日 00:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定