0

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 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

can you check my new question right here
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.