在 Flutter 和 Dart 中重构小部件的大多数 elegant/efficient 方法

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

在 "how to refactor Flutter widgets" 上在线搜索,我发现存在两种可能的方式,它们都按照我的测试运行,但从结构的角度来看仍然非常不同。第二种方法,确实包括额外的构建指令,这应该会给应用程序性能带来进一步的负担吧?

这是我要重构的代码:

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],
        ],),);

这些是我发现的主要方法:

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];
    }
}

哪种方法最好?

请看一看并考虑另一个问题:

简答:第二种方法更好(既高效又优雅)。


第一个方法(提取到一个函数)中,您只是创建了一个函数,return 封装的小部件。

第二种方法(提取到 class) 中,您正在将小部件提取到从 [=10= 扩展的新 class ].这种差异为Flutter框架提供了一种优化方法。