简体   繁体   English

如何有条件地将参数传递给 Flutter/Dart 中的 Widget?

[英]How do I conditionally pass argument to Widget in Flutter/Dart?

I want to conditionally pass an argument while using the widget.我想在使用小部件时有条件地传递一个参数。 Is there any way to do so?有什么办法吗?

...

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,
 );
},

...

I know we can conditionally pass the value as null using ternary operator here but what I am looking for is to skip the argument itself.我知道我们可以在这里使用三元运算符有条件地将值作为 null 传递,但我正在寻找的是跳过参数本身。

The above example is for ListTile widget.上面的示例适用于ListTile小部件。 But my curiosity is to know the syntax for doing so for any widget.但我的好奇心是知道为任何小部件执行此操作的语法。

Using optional named parameters , using parameter:value when a parameter is required pass its value else it can be skipped completely.使用optional named parameters ,在需要参数时使用parameter:value传递其值,否则可以完全跳过它。 Inside the called method null handling is required to be done by the developer(not handled internally).在调用的方法null内部需要由开发人员完成处理(内部不处理)。

This is a simplified sample:这是一个简化的示例:

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: Output:

Received => null : null
Received => 1 : null
Received => null : Printing
Received => 1 : Printing

Note: Default values can be assigned in the Widget/methods implementation and may not necessarily be always null .注意:可以在小部件/方法实现中分配默认值,并且不一定总是null

Example:例子:

void doNothing({int index, String description, String otherDesc = 'Provided By Default'}) {
  print('Received => $index : $description : $otherDesc ');
}

Output: Output:

Received => null : null : Provided By Default

Since not explicitly initialized variables in dart get automatically initialized to null (if they don't have a default value), for the widget there is no difference between not giving an argument to the optional parameter and giving the argument null .由于 dart 中未显式初始化的变量会自动初始化为null (如果它们没有默认值),对于小部件来说,不给可选参数提供参数和给参数null之间没有区别

Because of that setting it to null is actually skipping the argument.因为将其设置为null实际上是在跳过参数。 I would recommend just using the ternary operator in case you don't want to give an argument.如果您不想给出论点,我建议只使用三元运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM