问题描述
我在 Flutter 中创建了一个 TextFormField。我有一个名为 PartsData 的类,其中列出了一些属性。通过在另一个名为“RegistrationForm”的类中创建一个ParticipantsData 类的对象,我可以访问和存储所有这些属性中的值。但是,即使在初始化之后,我也无法将数据存储在 List 类型的属性中。
我试过了:
- List.filled()
- =[]
- =[""]
- List.generate()
- List()
- List<String>()
- List<String>(length)
我已经多次更改我的代码并尝试了很多方法,但似乎没有任何效果。我在这里发布的不多,因为我通常会在 stackoverflow 上找到解决方案,但这次我找不到任何东西。 无法发布整个代码,因为它太长了。相关代码如下:
参与者数据类:
class ParticipantsData {
List name = []; //members
bool paymentstatus = false; //payment
String email = ""; //email
String address = ""; //address
List contact = []; //contact
String collegename = ""; //collegename
String password = ""; //password
String teamname = ""; //teamname
var modules = List<String>(6); //modules
ParticipantsData({
this.name,this.email,this.contact,this.collegename,this.address,this.modules,this.password,this.paymentstatus,this.teamname,});
}
下面是Register类的相关代码:
class _RegistrationForm extends State<RegistrationForm> {
final ParticipantsData data = new ParticipantsData();
//This is the onSaved method of a TextFormField,which is in a loop.
(String value) { //Tried this...
data.name[i + 1] = value;
print('${data.name[i + 1]}');
}),(String value) { //And this too...
data.name.add(value);
print('${data.name[i + 1]}');
}),
解决方法
在构造函数内部初始化时,分配的值变为空。如果您不在构造函数中包含这些字段,它们将不重置为 null。
但是,如果在创建实例时未提供该字段,您可能希望在构造函数中分配值并需要一些默认值。操作方法如下:
class MyClass {
// Don't initialize here
List x;
int y;
MyClass({
this.x,this.y = 10,// If y is not assigned,it will take a default value of 10
}) {
// Constructor body
this.x = this.x ?? []; // If x is not assigned,it will take a value of []
}
}
注意 y 可以直接提供默认值,因为 10 是一个常数值。您只能在构造函数参数列表中分配常量默认值。由于 [ ] 不是常量表达式或值,不能直接赋值为默认值,因此需要定义构造函数体赋值 x = [ ] if x 为空。
this.x = this.x ?? [];
你可以用类似的方式初始化其他的。