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

Time:04-28

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

CodePudding user response:

Because you need to use a getter for that:

class Student {
  String name;
  Student({
    required this.name,
  });
  static Student get empty => Student(name: '');
}

CodePudding user response:

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