我正在嘗試創建幾個A都應屬于另一種型別的小部件的小部件B,以便最終將它們全部傳遞給只接受型別小部件B而不接受其他自定義小部件(如Container,Text等)的建構式。
我試過這樣的事情:
父類:
class ProDynamicWidget {
const ProDynamicWidget({
required this.height
});
final double height;
}
子班:
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();
}
}
我真的不明白現在如何以具有單獨構建方法的子小部件以及最終構造器僅接受這些子小部件而不是每種型別的小部件的方式結束。
uj5u.com熱心網友回復:
制作ProDynamicWidget abstract并讓它擴展StatelessWidget:
abstract class ProDynamicWidget extends StatelessWidget{
const ProDynamicWidget({
required this.height
});
final double height;
}
接下來,ProDynamicTitle簡單ProDynamicImage地擴展ProDynamicWidget,因此必須定義構建方法:
class ProDynamicTitle extends ProDynamicWidget {
final String title;
const ProDynamicTitle({
required this.title
}) : super(height: 50.0);
@override
Widget build(BuildContext context) {
return Text(title);
}
}
class ProDynamicImage extends ProDynamicWidget {
final String imageUrl;
const ProDynamicImage({
required this.imageUrl
}) : super(height: 70.0);
@override
Widget build(BuildContext context) {
return Image(image: NetworkImage(imageUrl));
}
}
你可以保持TestOneWidget原樣。它只接受ProDynamicWidget.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459978.html
上一篇:訪問作為模板的基類時的不同行為
