为什么 class 对象字符串的最后一个值分配给 flutter 中的第一个对象

Why Last value of a class object String assign to first one object in flutter

Click Here to see Dartpad Screenshot

void main(){
Student file1 = Student.empty;
Student file2 = Student.empty;
file1.name = 'ABC';
file2.name = 'DEF';
print(file1.name);
print(file2.name);
}
class Student{
String name;
Student({
required this.name,
});
static Student empty = Student(name: '');
}

输出值

防御 防御

预期价值

美国广播公司 防御

发生这种情况是因为您正在使用 Student 的相同 static 实例,因为静态字段在 Student.

的所有实例之间共享

因此您的变量 file1file2 引用了 Student 的同一个实例。

您可能想改用工厂构造函数:

https://dart.dev/guides/language/language-tour#factory-constructors

void main() {
  Student file1 = Student.empty();
  Student file2 = Student.empty();
  file1.name = 'ABC';
  file2.name = 'DEF';
  print(file1.name);
  print(file2.name);
}

class Student {
  String name;
  Student({
    required this.name,
  });
  
  factory Student.empty() {
    return Student(name: '');
  }
}