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

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


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