简体   繁体   English

Flutter 中的 StatefulBuilder VS StatefulWidget - 性能

[英]StatefulBuilder VS StatefulWidget in Flutter - performance

We can use StatefulBuilder to update a specific element on the UI of a StatelessWidget and in other hand, we can archive similar result moving the StatelessWidget to a StatefulWidget and getting rid of the StatefulBuilder widget.我们可以使用StatefulBuilder来更新StatelessWidget的 UI 上的特定元素,另一方面,我们可以存档类似的结果,将StatelessWidget移动到StatefulWidget并摆脱StatefulBuilder小部件。

I prefer StatefulBuilder because it makes the code much easier and cleaner, but what's the best in terms of performance ?我更喜欢StatefulBuilder因为它使代码更简单、更清晰,但在性能方面什么是最好的

A : Wrap everything on a StatefulBuilder using StatelessWidget A : 使用StatelessWidget将所有内容包装在StatefulBuilder

B : Use StatefulWidget B : 使用StatefulWidget

There is effectively no difference in performance between the two.两者之间的性能实际上没有差异。 Both involve the creation of a State object.两者都涉及创建 State 对象。

Given that your using global state, there is no real reason to use a StatefulBuilder relating to part of that existing global state.鉴于您使用全局状态,没有真正的理由使用与现有全局状态的一部分相关的 StatefulBuilder。 The StatefulBuilder provides a mechanism to have its own associated State object with state you define and can mutate. StatefulBuilder 提供了一种机制,可以将自己的关联 State 对象与您定义的状态关联起来并且可以改变。 In your case (global data), your state is already in memory, so you might as well just mutate it in your StatefulBuilder builder callback, eg在您的情况(全局数据)中,您的状态已经在内存中,因此您不妨在 StatefulBuilder 构建器回调中对其进行变异,例如

setState(() => myGlobalCounter.increment());

You are likely aware, that one would normally prefer an InheritedWidget based state solution.您可能知道,人们通常更喜欢基于 InheritedWidget 的状态解决方案。 While this can be considered equivalent in some ways to just moving global state to a global tree location, it more easily allows for all interested Widgets to be notified of changes to that state.虽然这在某些方面可以被认为等同于将全局状态移动到全局树位置,但它更容易允许所有感兴趣的 Widget 被通知该状态的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM