flutterdartrefactoring

Most elegant/efficient way to refactor widgets in Flutter and Dart


Searching online on "how to refactor Flutter widgets" I found that there exist two possible ways that are both functioning as per my testing, still very different from a structural standpoint. The second method, indeed includes and additional building instruction, which should bring a further burden on the app performances right?

This is the code I want to refactor:

Container(
    child: Column(
        children: <Widget> [
            [long code to create a button with many properties],
            [long code to create a button with many properties],
            [long code to create a button with many properties],
            [long code to create a button with many properties],
        ],),);

These are the main ways I found:

1):

Widget MyButton(Color color, String text) {
    return [long code to create a button with many properties];
}

2):

class MyButton extends StatelessWidget {
    MyButton(this.color, this.text);

    final Color color;
    final String text;

    @override
    Widget build(BuildContext context) {
        return [long code to create a button with many properties];
    }
}

Which is the best method?


Solution

  • Please take a look and consider this other question:

    What is the difference between functions and classes to create reusable widgets?

    Short answer: It' better the second method (both efficient and elegant).


    In the first method (extract to a function), you are just creating a function that return the encapsulated widget.

    In the second method (extract to a class), you are extracting the widget to a new class that extends from StatelessWidget. This difference gives to the Flutter framework a way to make optimizations.