Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 234
scugn1zz0 Avatar asked Oct 24 '25 21:10

scugn1zz0


1 Answers

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.

like image 101
encubos Avatar answered Oct 26 '25 10:10

encubos



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!