如何在 Flutter 中创建自定义类型的 widget?
我正在尝试创建几个小部件 A
,它们都应该属于另一种类型的小部件 B
,以便最终所有它们都可以传递给构造函数仅接受 B
类型的小部件,但不接受其他自定义小部件,例如 Container
、Text
等。
我尝试了这样的操作:
Parent class:
class ProDynamicWidget {
const ProDynamicWidget({
required this.height
});
final double height;
}
Child类:
class ProDynamicTitle extends ProDynamicWidget {
final String title;
ProDynamicTitle({
required this.title
}) : super(height: 50.0);
// Here should be a build method for the title
}
############################################################
class ProDynamicImage extends ProDynamicWidget {
final String imageUrl;
ProDynamicImage({
required this.imageUrl
}) : super(height: 70.0);
// Here should be a build method for the image
}
然后我想创建一个仅接受类型小部件的小部件ProDynamicWidget:
class TestOneWidget extends StatelessWidget {
const TestOneWidget({
Key? key,
required this.widget
}) : super(key: key);
final ProDynamicWidget widget;
@override
Widget build(BuildContext context) {
return Container();
}
}
我真的不明白现在如何才能得到具有单独构建方法的子小部件,以及最后的构造器仅接受这些子小部件而不是每种类型的小部件的方式。
I am trying to create a couple of widgets A
that all should belong to another type of widget B
, so that in the end all of them could be passed to a constructor that accepts only widgets of type B
, but not other custom widgets like Container
, Text
, etc.
I tried something like this:
Parent class:
class ProDynamicWidget {
const ProDynamicWidget({
required this.height
});
final double height;
}
Child classes:
class ProDynamicTitle extends ProDynamicWidget {
final String title;
ProDynamicTitle({
required this.title
}) : super(height: 50.0);
// Here should be a build method for the title
}
############################################################
class ProDynamicImage extends ProDynamicWidget {
final String imageUrl;
ProDynamicImage({
required this.imageUrl
}) : super(height: 70.0);
// Here should be a build method for the image
}
I then wanted to create a widget that only accept widgets of type ProDynamicWidget:
class TestOneWidget extends StatelessWidget {
const TestOneWidget({
Key? key,
required this.widget
}) : super(key: key);
final ProDynamicWidget widget;
@override
Widget build(BuildContext context) {
return Container();
}
}
I do not really get how can now end up with child widgets that have separate build methods and a way the constructur at the end only accepts these child widgets instead of every type of widget.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使
ProDynamicWidget
abstract
并让它扩展StatelessWidget
:接下来,简单地
ProDynamicTitle
和ProDynamicImage
扩展ProDynamicWidget
,因此必须定义构建方法:您可以保持
TestOneWidget
不变。它只接受ProDynamicWidget
的后代。Make
ProDynamicWidget
abstract
and let it extendStatelessWidget
:Next,
ProDynamicTitle
andProDynamicImage
simply extendProDynamicWidget
and will thus have to define the build method:You can keep
TestOneWidget
as is. It will only accept descendants ofProDynamicWidget
.