简体   繁体   中英

Should Flutter widgets be created in the class or in the build() function?

Is there a general rule of thumb on where to create widgets to be more optimal (assuming the widget doesn't rely on anything passed into build())?

If we create a Widget inside the class:

Foo({Key key}) : super(key: key);
Widget _widget = new Container(); // Create here?

we only create it once when the class is created. However, this widget may sit around taking up space if it isn't always being used in build() (eg an offstage widget, or the visibility of the widget is determined by a flag).

If we create the widget inside build():

@override
Widget build(BuildContext context) {
Widget widget = new Container(); // Or create here?
  return widget;
}

The widget gets re-created on every build() call, which feels costly, especially if the widget isn't changing.

Constructing short-lived objects is generally very cheap in Flutter/Dart, and the widgets layer takes care of making sure that the render tree isn't modified on rebuilds unless the widget changes. So caching widgets doesn't help much in normal situations. I'd lean towards constructing widgets in your build() method unless there's a reason why that won't work.

There's usually no need to care about this optimisation. But use the const constructor whenever possible.

But keep in mind that you should use your models as widgets directly. You shouldn't have a Widget that take an instance of your model class as input. It's instead your model class that should have a build method. Consequence, when storing data in your state, you won't have to recreate a new widget everytimes Build is called.

A good example is the list of ChatMessage in flutter's codelab. https://codelabs.developers.google.com/codelabs/flutter/index.html#5

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