Any idea how to assign a default parameter to a function aside of Map
parameter in dart?
static Future functionName(
bool isDone,
[
Map<String, String> params,
]
) async {
....
}
Note that if I put functionName([...],{bool isDone = false})
it doesn't work until I remove [...],
If you want isDone
to have a default value, that means it will need to become an optional parameter. Your function has an existing optional positional parameter ( params
), and Dart currently does not allow mixing optional positional parameters with optional named parameters . Therefore for isDone
to be optional, it also must be positional. To avoid breaking existing callers, it should remain the first parameter:
static Future functionName([
bool isDone = false,
Map<String, String>? params, // Remove the `?` if you don't enable null-safety.
]) async {
....
}
and then you would call it the same way that you already do:
functionName(
true,
{
'key1': value1,
'key2': value2,
...
},
);
The only difference between this and your existing code is that you now will be able to call your function as just functionName()
. If you want callers to be able to call your function with params
but not with isDone
, then that would be a breaking change (you would need to update all callers) and would require reordering the parameters or changing the parameters to optional named parameters.
A friend helped me with this and figured out that function args can take default values have to be given inside [] or {}, so this is how we pass it:
static Future functionName(
[
Map<String, String> params,
bool isDone = false,
]
) async {
....
}
And call it like this:
functionName(
{
'key1': value1,
'key2': value2,
...
},
true,
);
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.