Is there a way to pass a primitive parameter by reference in Dart?

The Dart language does not support this and I doubt it ever will, but the future will tell.

Primitives will be passed by value, and as already mentioned here, the only way to ‘pass primitives by reference’ is by wrapping them like:

class PrimitiveWrapper {
  var value;
  PrimitiveWrapper(this.value);
}

void alter(PrimitiveWrapper data) {
  data.value++;
}

main() {
  var data = new PrimitiveWrapper(5);
  print(data.value); // 5
  alter(data);
  print(data.value); // 6
}

If you don’t want to do that, then you need to find another way around your problem.

One case where I see people needing to pass by reference is that they have some sort of value they want to pass to functions in a class:

class Foo {
  void doFoo() {
    var i = 0;
    ...
    doBar(i); // We want to alter i in doBar().
    ...
    i++;
  }

  void doBar(i) {
    i++;
  }
}

In this case you could just make i a class member instead.

Leave a Comment