[英]Flutter, how to reduce repeated widget
謝謝你幫助我。
我想要做的是減少下面代碼的重復;
class PeddingRadius extends StatelessWidget {
PeddingRadius(final column);
@override
Widget build(BuildContext context) {
Container(
padding: const EdgeInsets.all(8.0),
child: Material(
borderRadius: BorderRadius.circular(30),
shadowColor: Colors.grey.shade100,
elevation: 5,
child: //my code
),
)
}
}
有沒有辦法可以在函數或方法上方創建並插入下面的代碼?
Image.asset(
'asset/images/HelloWorld.png', height: 100.0, width: 100.0,
),
Text('Hello World, form Dart'),
您可以只使用一個函數將您的代碼作為小部件返回
Widget myWidget(String assetLocation, String text) {
return Container(
padding: const EdgeInsets.all(8.0),
child: Material(
borderRadius: BorderRadius.circular(30),
shadowColor: Colors.grey.shade100,
elevation: 5,
child: Column(
children: [
Image.asset(
assetLocation, height: 100.0, width: 100.0,
),
Text(text),
],
)
),
);
}
然后只需使用myWidget('asset/images/HelloWorld.png', 'Hello World, form Dart')
只需將子屬性添加到PeddingRadius
。
class PeddingRadius extends StatelessWidget {
final Widget child;
PeddingRadius({@required Widget child});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(8.0),
child: Material(
borderRadius: BorderRadius.circular(30),
shadowColor: Colors.grey.shade100,
elevation: 5,
child: child,
),
);
}
}
然后給它任何你想要的孩子。
PeddingRadius(
child: Column(
children: [
Image.asset(
assetLocation, height: 100.0, width: 100.0,
),
Text(text),
],
),
)
// or
PeddingRadius(
child: RaisedButton(child: Text("Hello World")),
)
這與@dkap 的答案基本相同,有一個自己的小部件類,並且具有更多的可重用性,因為它接受各種子項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.