Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 997
Mary Avatar asked Oct 17 '25 11:10

Mary


1 Answers

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.

like image 192
Collin Jackson Avatar answered Oct 20 '25 03:10

Collin Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!