简体   繁体   中英

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.

The above example is for ListTile widget. 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. Inside the called method null handling is required to be done by the developer(not handled internally).

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:

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 .

Example:

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

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 .

Because of that setting it to null is actually skipping the argument. I would recommend just using the ternary operator in case you don't want to give an argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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