Home > Enterprise >  How to set New Variable value from Old Variable value, if New Variable value changed the Old Variabl
How to set New Variable value from Old Variable value, if New Variable value changed the Old Variabl

Time:12-05

As stated in the title

Look at this code Example:

void main() {
  final Student student = Student('Lincoln', 29);
  print('Student before $student');

  final Student newStudent = student;
  newStudent?.name = 'Abraham';
  print('new Student $newStudent'); /// 'Abraham', 29
  print('Student after $student'); /// 'Abraham', 29 - but I need this output still 'Lincoln', 29
}


class Student {
  Student(this.name, this.age);
  
  String? name;
  int? age;
  
  @override
  String toString() => '$name, $age';
}

From the code above if we set newStudent and make changes, the student variable also follows the changes, but I don't want the student variable changed. How to solve this?

CodePudding user response:

You should make a new Student instance for the new one. If you want it to have the same name as age as the old you could do this for example:

final Student newStudent = Student(student.name, student.age);

CodePudding user response:

and also study this example..this will clear the concept...

 final List<int> numbers=[1,2,3];

  print(numbers);

  final List<int> numbers2=numbers;

  numbers2.add(100);//this will add also to numbers
  print(numbers);

  //so use following for keep original array as it was

  final List<int> numbers3=[...numbers];//user this spread operator

  numbers3.add(200);

  print(numbers);

so what u have to focus is

we passing reference not value by this statement

Student newstudent=&student (like in C language, here & sign is not used in dart
  • Related