简体   繁体   中英

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.

I prefer StatefulBuilder because it makes the code much easier and cleaner, but what's the best in terms of performance ?

A : Wrap everything on a StatefulBuilder using StatelessWidget

B : Use StatefulWidget

There is effectively no difference in performance between the two. Both involve the creation of a State object.

Given that your using global state, there is no real reason to use a StatefulBuilder relating to part of that existing global state. The StatefulBuilder provides a mechanism to have its own associated State object with state you define and can mutate. 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

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

You are likely aware, that one would normally prefer an InheritedWidget based state solution. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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