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

2,586

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.

Share:
2,586
Mary
Author by

Mary

Updated on December 03, 2022

Comments

  • Mary
    Mary over 1 year

    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.