Flutter pass parameter by reference

Passing Parameters by Reference in Flutter

In Flutter, by default, all function arguments are passed by value. It means that only the value of the variable is passed to the function, and any modifications made to the parameter within the function do not affect the original variable.

However, if you want to pass a parameter by reference, you can achieve it by using a wrapper object or a callback function. Let’s explore both approaches with examples:

1. Using a Wrapper Object

You can create a custom class or use an existing class to wrap the value you want to modify.

    
      class ValueWrapper {
        int value;
      
        ValueWrapper(this.value);
      }
      
      void modifyValue(ValueWrapper wrapper) {
        wrapper.value = 10; // Modifying the value
      }
      
      void main() {
        ValueWrapper wrapper = ValueWrapper(5);
        print(wrapper.value); // Output: 5
      
        modifyValue(wrapper);
        print(wrapper.value); // Output: 10 - value modified
      
        // The original variable is modified due to passing by reference using the wrapper object.
      }
    
  

In the above example, we create a class called ValueWrapper that wraps the integer value. The modifyValue() function takes a ValueWrapper object as a parameter and modifies the value. When we pass the wrapper object to the function, any changes made to the value within the function will reflect on the original variable.

2. Using a Callback Function

You can also achieve the pass-by-reference behavior by using a callback function. This approach is useful when you want to modify a parameter based on some conditions.

    
      void modifyValue(Function(int) callback) {
        callback(10); // Invoke the callback function with the modified value
      }
      
      void main() {
        int value = 5;
        print(value); // Output: 5
      
        modifyValue((newValue) {
          value = newValue;
        });
      
        print(value); // Output: 10 - value modified
      
        // The original variable is modified due to passing by reference using the callback function.
      }
    
  

In the above example, the modifyValue() function takes a callback function as a parameter. Within the function, we invoke the callback function with the modified value, and outside the function, we define the callback function to modify the original variable.

Using the above approaches, you can achieve pass-by-reference behavior in Flutter when needed.

Leave a comment