Should Flutter widgets be created in the class or

2019-07-23 17:44发布

问题:

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() (e.g. 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.

回答1:

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.



回答2:

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