gpt4 book ai didi

flutter - 使用默认值初始化类参数

转载 作者:行者123 更新时间:2023-12-03 04:51:08 29 4
gpt4 key购买 nike

如何使用默认值初始化类参数

void main() {
Test t = Test();
print(t.l); //<-prints null, should print []
}

class Test{
List l=[];
Test({this.l});
}

我认为这以前对我有用,但由于某种原因,现在不起作用
void main() {
Test t = Test();
print(t.l);
}

class Test{
List l;
Test({this.l}) : l = l ?? []; //<- as from GitHub this doesn't work either
}

最佳答案

如VyacheslavEgorov所述,执行此操作的最佳方法是通过初始化程序,如果您不希望使用const默认值

并且它的工作原理,当您删除构造函数是根据github上的this问题是:

When you write f({this.x}) that means f({this.x : null}).

Default initializers can only be constants, so your best bet is f({List x}) : x = x ?? [];



所以会像这样:
class MyListClass {
List myList;

MyListClass({List myList}) : this.myList = myList ?? [];
}

关于flutter - 使用默认值初始化类参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61303649/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com