【发布时间】:2022-08-19 22:31:49
【问题描述】:
我创建了一个小部件,根据其FocusNode 的焦点,它要么变为TextField,要么变为Text。它工作得很好,here is the code(这里没有把它包括在内)。
问题是,Text 和 TextField 有很多参数来设置它们的样式,我发现将所有这些参数复制到我的新混合小部件的构造函数中只是为了将它们传递给新的这两个小部件并不是最佳选择build 方法而不对它们做任何其他事情。
例如TextField 在其构造函数中有超过 50 个参数,这是将它与另一个小部件组合并仍然获得所有这些选项以设置 TextField 样式的唯一方法,是将这些参数中的每一个复制到我的构造函数中,然后除了将它们传递给TextField 之外,没有对它们做任何事情?
那么是否有一些设计模式或一些解决方案可以让这两个小部件的参数在新小部件的构造函数中可用?
注意:请参阅comment of M. Azyoksul on Gunter\'s comment here 以获取更多上下文。
问题的最小示例:
// this widget is from external library (not under my control)
class WidgetA extends StatelessWidget {
// very long list of fields
A1 a1;
A2 a2;
... (long list of fields)
// constructor
WidgetA(this.a1, this.a2, ...);
}
// this widget is from external library
class WidgetB extends StatelessWidget {
// very long list of fields
B1 b1;
B2 b2;
... (long list of fields)
// constructor
WidgetB(this.b1, this.b2, ...);
}
// now this is the widget I want to create
class HybridWidget extends StatelessWidget {
// time consuming: I copy all the fields of WidgetA and
// WidgetB into the new constructor just to pass them as they are without doing anything else useful on them
A1 a1;
A2 a2;
...
B1 b1;
B2 b2;
...
// the new constructor: (not optimal at all)
HybridWidget(this.a1,this.a2,...,this.b1,this.b2,...);
@override
Widget build(BuildContext context) {
// for example:
if(some condition)
return Container(child:WidgetA(a1,a2, ...),...); <--- here is the problem, I am not doing anything other than passing the \"styling\" parameters as they were passed to me, alot of copy/paste
if(other condition)
return Container(Widget2(b1,b2, ... ),...); <--- and here is the same problem
//... other code
}
}
标签: android flutter dart design-patterns