[英]How do I pass the value selected from DropDown menu to a stateful widget right below it in Flutter/Dart?
[英]How do I conditionally pass argument to Widget in Flutter/Dart?
我想在使用小部件時有條件地傳遞一個參數。 有什么辦法嗎?
...
return ListTile(
title: Text("${product.name}"),
// want to conditionally pass subtitle, which is not the right syntax (???)
if(condition) subtitle: Text("subtitle"),
// I know about this
subtitle: condition? Text("subtitle"): null,
);
},
...
我知道我們可以在這里使用三元運算符有條件地將值作為 null 傳遞,但我正在尋找的是跳過參數本身。
上面的示例適用於ListTile
小部件。 但我的好奇心是知道為任何小部件執行此操作的語法。
使用optional named parameters
,在需要參數時使用parameter:value
傳遞其值,否則可以完全跳過它。 在調用的方法null
內部需要由開發人員完成處理(內部不處理)。
這是一個簡化的示例:
void main() {
doNothing();
doNothing(index: 1);
doNothing(description: 'Printing');
doNothing(index: 1,description: 'Printing');
}
void doNothing({int index, String description}) {
print('Received => $index : $description');
}
Output:
Received => null : null
Received => 1 : null
Received => null : Printing
Received => 1 : Printing
注意:可以在小部件/方法實現中分配默認值,並且不一定總是null
。
例子:
void doNothing({int index, String description, String otherDesc = 'Provided By Default'}) {
print('Received => $index : $description : $otherDesc ');
}
Output:
Received => null : null : Provided By Default
由於 dart 中未顯式初始化的變量會自動初始化為null
(如果它們沒有默認值),對於小部件來說,不給可選參數提供參數和給參數null
之間沒有區別
因為將其設置為null
實際上是在跳過參數。 如果您不想給出論點,我建議只使用三元運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.