Reputation: 954
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.
Upvotes: 12
Views: 6265
Reputation: 1381
The answer I wanted is in the question
subtitle: condition ? Text("subtitle"): null,
Upvotes: 2
Reputation: 271
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.
Upvotes: 0
Reputation: 1288
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
Upvotes: 2