Flutter pass by reference

Flutter Pass By Reference

In Flutter, all function arguments are passed by value. This means that when you pass an argument to a function, a copy of the value is made and passed to the function. Any modifications made to the parameter inside the function will not affect the original value.

However, when you pass an object as an argument, the reference to the object is passed by value. This means that the reference to the object is copied and passed to the function. Any changes made to the object’s properties inside the function will be reflected in the original object.

Let’s see an example to understand pass by reference in Flutter:


class Person {
  String name;
  
  Person(this.name);
}

void changeName(Person person, String newName) {
  person.name = newName;
}

void main() {
  Person person = Person('John');
  print(person.name); // Output: John
  
  changeName(person, 'Mike');
  print(person.name); // Output: Mike
}
    

In the above example, we have a class Person with a property name. The function changeName takes a Person object and a newName string. Inside the function, we modify the name property of the Person object. As the Person object is passed by reference, the changes made inside the function are reflected in the original object.

However, if we pass a primitive data type like int or string, any modifications made to the parameter inside the function will not affect the original value. For example:


void changeInt(int value) {
  value = 10;
}

void main() {
  int number = 5;
  print(number); // Output: 5
  
  changeInt(number);
  print(number); // Output: 5
}
    

In this example, the function changeInt takes an int value. Inside the function, we change the value to 10. However, as int is passed by value, the original value of number remains unchanged.

Leave a comment