我可以问吗?我正在研究带有可选参数的 dart 函数语言。当我运行此代码时出现错误,并且我很困惑如何修复它。你能帮我解决这个问题吗:
void gfg1(int g1, [ int g2 ])
{
// Creating function 1
print("g1 is $g1");
print("g2 is $g2");
}
void gfg2(int g1, { int g2, int g3 })
{
// Creating function 1
print("g1 is $g1");
print("g2 is $g2");
print("g3 is $g3");
}
void gfg3(int g1, { int g2 : 12 })
{
// Creating function 1
print("g1 is $g1");
print("g2 is $g2");
}
void main()
{
// Calling the function with optional parameter
print("Calling the function with optional parameter:");
gfg1(01);
// Calling the function with Optional Named parameter
print("Calling the function with Optional Named parameter:");
gfg2(01, g3 : 12);
// Calling function with default valued parameter
print("Calling function with default valued parameter");
gfg3(01);
}
问题:
The parameter 'g2' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
The parameter 'g3' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
这是我的 dart 版本:Dart SDK 版本:2.12.0-179.0.dev (dev)(2020 年 12 月 23 日星期三 21:08:22 -0800)在“windows_x64”上
参考:https://www.geeksforgeeks.org/dart-programming-functions/?ref=rp
欢迎来到 Dart。您所看到的是 Dart 2.12.0 附带的新空安全功能的一部分。您可以在此处阅读有关详细信息的更多信息: https://dart.dev/null-safety
可选变量的问题在于它们是可选的。那么如果它们没有设置任何值,我们给它们什么值呢?好吧,你可以像这里一样设置默认值(只是想补充一下,这是不再推荐的旧语法,你应该使用
int g2 = 12
):
void gfg3(int g1, { int g2 : 12 })
因此在这种情况下,如果我们不给
g2
任何值,它将自动获取值 12
。这可以。怎么样:
void gfg2(int g1, { int g2, int g3 })
这就是问题所在,因为
int
是(在 Dart 2.12 中)永远不可能是 null
的类型。但未设置的可选参数的默认值为 null
。
您可以做的是通过使用类型
g2
来允许 g3
和 int?
为空,该类型是 int
但允许值 null
:
void gfg2(int g1, { int? g2, int? g3 })
或者,您可以说该值是命名参数,但不再是可选的:
void gfg2(int g1, { required int g2, required int g3 })
或者给出一个默认的非空值:
void gfg2(int g1, { int g2 = 0, int g3 = 0 })
将代码粘贴到 DartPad 上不会给我带来任何错误,并且会输出预期的结果。我很好奇为什么要使用开发版而不是稳定版?即使用稳定版本。
来自dart官方网站:
开发频道版本是最新的,包含最新的更改,可能已损坏、不受支持,并且可能包含未经审查的重大更改。
PS:DartPad 使用:Dart SDK 2.10.4
参见https://dart.dev/language/functions
void func(int requiredParam, [int optionalParam = 0]){
...
}