scugn1zz0
scugn1zz0

Reputation: 337

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?

Upvotes: 4

Views: 4721

Answers (2)

Kelv1nG
Kelv1nG

Reputation: 67

Its also worth noting that the flutter team recommends using class based widgets rather than functional widgets

mainly

  1. optimized rebuilds from state changes
  2. easier to test widgets

here is a vid link to it discussed by flutter team

https://www.youtube.com/watch?v=IOyq-eTRhvo

Upvotes: 0

encubos
encubos

Reputation: 3303

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.

Upvotes: 4

Related Questions