Flutter: Is there a difference between a function that returns a widget and the Extract Widget that create a class?

Viewed 997

Is there a diference between a function that returns a widget and the Extract Widget that create a class? in terms of performance, best practices, etc.

At first sight I would prefer the function, because is les bulky, but I want to hear your opinions.

Custom Function

Container box() {
  return Container(
    margin: EdgeInsets.all(15.0),
  );
}

This is produced by using the Extract Widget

class BoxExtracted extends StatelessWidget {
  const BoxExtracted({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15.0),
    );
  }
}
1 Answers

The function is just a function which creates widgets.

The class is an actual widget. With a life cycle which will include all optimizations which come from it. Just because you create an instance of your widget also doesn't mean that it is always rebuilt, while the function obviously will always execute imediately.

from the API Documentation

The build method of a stateless widget is typically only called in three situations: the first time the widget is inserted in the tree, when the widget's parent changes its configuration, and when an InheritedWidget it depends on changes.

Related