在网上搜索“如何重构Flutter小部件”时,我发现存在两种可能的方法,根据我的测试,它们都在起作用,但从结构的角度来看,仍然有很大的不同。第二种方法确实包括附加的构建说明,这应该给应用程序性能带来更多负担吗?
这是我要重构的代码:
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];
}
}
哪个是最好的方法?
简短回答:最好是第二种方法(既高效又优雅)。
在
第一个方法(提取到一个函数)中,您只是创建一个返回封装的小部件的函数。
在第二种方法(提取到一个类)中,您要将小部件提取到一个从StatelessWidget
扩展的新类中。这种差异为Flutter框架提供了一种进行优化的方法。