ouai
ouai

Reputation: 189

Dart : change reference of object

This doesn't change the value of 'myStuff.stuff', its value is still 'start' :

void main() {

 Thing myStuff = Thing();
 myStuff.stuff = 'start';
 doStuff(myStuff);
 print(myStuff.stuff);

}

void doStuff(Thing theStuff) {
 theStuff = Thing();
 theStuff.stuff = 'test';
}

class Thing {
 String stuff = '';
}

How can I replace the referenced object in a function ?

Upvotes: 0

Views: 736

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17143

You cannot do this in the method that you show. Dart is not pass by reference. It is pass by value.

If you want to be able to do something similar to this, you can either wrap your Thing object with a another object or provide a callback that modifies your original object.

Something along these lines for the wrapper class method:

void main() {
  Thing myStuff = Thing();
  myStuff.stuff = 'start';
  
  ThingWrap wrapper = ThingWrap();
  wrapper.thing = myStuff;
  
  doStuff1(wrapper);
  
  print(wrapper.thing.stuff);
}

void doStuff1(ThingWrap theStuff) {
 var newStuff = Thing();
 newStuff.stuff = 'test';
  
  theStuff.thing = newStuff;
}

class Thing {
 String stuff = '';
}

class ThingWrap {
  Thing thing = Thing();
}

or the callback method:

void main() {
  Thing myStuff = Thing();
  myStuff.stuff = 'start';
  
  doStuff1((newVal) {
    myStuff = newVal;
  });
  
  print(myStuff.stuff);
}

void doStuff1(Function(Thing) callback) {
  var newStuff = Thing();
  newStuff.stuff = 'test';
  callback(newStuff);
}

class Thing {
 String stuff = '';
}

It's not immediately clear why you would want to do this based on the example you provided. If this were provided, it may have been possible to provide a cleaner solution. Simply providing a return value for doStuff and assigning it to myStuff in main would seem like the obvious way to do the same thing.

Upvotes: 2

Related Questions