4

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),
    );
  }
}
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
Tapioca
  • 309
  • 3
  • 7
  • I always start from first method, and then If I found out the similar widget used frequently, and changed to second method, and made It more customizable. By the way, there are many aspects to discuss this issue, It might be good on test If you start on second method. – Tokenyet Oct 01 '19 at 04:57
  • 2
    Possible duplicate of [What is the difference between functions and classes to create widgets?](https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-widgets) – ibhavikmakwana Oct 01 '19 at 05:55
  • brother take a look : Rémi talked about here: https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-reusable-widgets – Paras Arora Jul 29 '20 at 06:41
  • https://stackoverflow.com/a/53234826/700648 https://youtu.be/IOyq-eTRhvo – Sam Jun 24 '22 at 18:44

1 Answers1

0

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.

Herbert Poul
  • 4,512
  • 2
  • 31
  • 48