[英]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.在网上搜索“如何重构 Flutter 小部件”,我发现根据我的测试,存在两种可能的方式,但从结构的角度来看仍然有很大不同。 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): 1):
Widget MyButton(Color color, String text) {
return [long code to create a button with many properties];
}
2): 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?哪种方法最好?
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.在第一种方法(提取到函数)中,您只是创建了一个返回封装小部件的 function。
In the second method (extract to a class) , you are extracting the widget to a new class that extends from StatelessWidget
.在第二种方法(提取到类)中,您将小部件提取到从StatelessWidget
扩展的新 class 。 This difference gives to the Flutter framework a way to make optimizations.这种差异为 Flutter 框架提供了一种进行优化的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.