如何将窗口小部件构造函数作为参数传递给另一个窗口小部件来构建 [英] How to pass widget constructor as a parameter for another widget to build
问题描述
是否可以将一个小部件作为参数传递给另一个小部件?
Is there a way to pass one widget as a parameter to another?
我的代码与此类似,有两个 TextWidget
类型为 BoldWidget
和 ItalicWidget
:
My code has something similar to this with two TextWidget
of type BoldWidget
and ItalicWidget
:
abstract class TextWidget extends StatelessWidget {
final String text;
TextWidget({
@required this.text,
});
}
class BoldWidget extends TextWidget {
@override
Widget build(BuildContext context) {
return Text(this.text, style: TextStyle(fontWeight: FontWeight.bold),);
}
}
class ItalicWidget extends TextWidget {
@override
Widget build(BuildContext context) {
return Text(this.text, style: TextStyle(fontStyle: FontStyle.italic),);
}
}
在运行时,我想将 TextWidget
作为参数传递给另一个小部件( TextDisplay
),如下所示:
At runtime, I want to pass in either TextWidget
as an argument to another widget (TextDisplay
) like this:
class TextDisplay extends StatelessWidget {
final TextWidget widget;
final String string;
const TextDisplay({Key key, this.widget, this.string}) : super(key: key);
@override
Widget build(BuildContext context) {
return widget(string);
}
}
上面的代码中无效的是 widget(string)
,错误消息为'widget'不是函数".
What doesn't work in the code above is widget(string)
, with error message "'widget' isn't a function".
如何将一个小部件作为另一个参数传递,以便可以由另一个类构造它?
How can I pass one widget as another argument so it can constructed by another class?
我的实际代码无法在将 TextWidget
传递给 TextDisplay
之前构建 TextWidget
,因为 TextDisplay
需要将某些参数应用于 TextWidget
.
My actual code can't build the TextWidget
before passing it to TextDisplay
as TextDisplay
needs to apply some of the arguments to the TextWidget
.
推荐答案
您可以使用typedef来使用CallBack模式:
You can use the CallBack pattern using typedef :
typedef CustomCallBack = TextWidget Function(String value);
class TextDisplay extends StatelessWidget {
final CustomCallBack widget;
final String string;
const TextDisplay({Key key, this.widget, this.string}) : super(key: key);
@override
Widget build(BuildContext context) {
return widget(string);
}
}
这篇关于如何将窗口小部件构造函数作为参数传递给另一个窗口小部件来构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!