skip to Main Content

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?

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search