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

Viewed 53

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: '');
}

Output Value

DEF DEF

Expected Value

ABC DEF

1 Answers

This happens, because you are using the same static instance of Student, since the static field is shared across all instances of Student.

So your variables file1 and file2 are referencing the same single instance of Student.

You may want to use a factory constructor instead:

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: '');
  }
}
Related