简体   繁体   English

如何在 dart 中将默认参数分配给除 map 参数之外的函数

[英]How to assign a default parameter to a function aside of map parameter in dart

Any idea how to assign a default parameter to a function aside of Map parameter in dart?知道如何将默认参数分配给飞镖中Map参数之外的函数吗?

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 [...],请注意,如果我输入functionName([...],{bool isDone = false})它在我删除[...],

If you want isDone to have a default value, that means it will need to become an optional parameter.如果你希望isDone有一个默认值,这意味着它需要成为一个可选参数。 Your function has an existing optional positional parameter ( params ), and Dart currently does not allow mixing optional positional parameters with optional named parameters .你的函数有一个现有的可选位置参数( params ), Dart 目前不允许将可选位置参数与可选命名参数混合 Therefore for isDone to be optional, it also must be positional.因此isDone是可选的,它也必须是位置的。 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() .这与您现有代码之间的唯一区别是您现在可以将您的函数调用为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.如果您希望调用者能够使用params不是使用isDone调用您的函数,那么这将是一个重大更改(您需要更新所有调用者)并且需要重新排序参数或将参数更改为可选的命名参数。

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:一位朋友帮我解决了这个问题,发现函数 args 可以采用默认值,必须在 [] 或 {} 中给出,所以我们是这样传递它的:

static Future functionName(
  [
    Map<String, String> params,
    bool isDone = false,
  ]
) async {
    ....
}

And call it like this:并这样称呼它:

functionName(
  {
    'key1': value1,
    'key2': value2,
    ...
  },
  true,
);

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

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