[英]Conditionally pass optional parameter to widget
我有一個自定義小部件,可以選擇傳遞size
屬性。 如果存在,此值應傳遞給我自己的小部件中Icon()
小部件的size
屬性。
如果它存在,有沒有辦法只傳遞這個值?
class MyWidget extends StatelessWidget {
final double size;
MyWidget({this.size});
Widget build(BuildContext context) {
return Icon(
iconData: IconData(),
size: // Don't pass size here if not present
);
}
}
我遇到了類似的問題,我必須選擇在按鈕中顯示一個圖標。
在 null 安全的情況下,您可以通過這種方式實現您想要做的事情
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
final double? size;
MyWidget ({this.size});
Widget build(BuildContext context) {
return Icon(
iconData:IconData(),
size: size, // Don't pass size here if not present
);
}
}
並像這樣使用
StackIcon()
或者像這樣
StackIcon(size: 100.0)
If you supply the size parameter the icon will make use of it, otherwise it uses the default size of the icon.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.