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

后端 未结 4 565
既然无缘
既然无缘 2020-12-01 17:51

I would like to pass a primitive (int, bool, ...) by reference. I found a discussion about it (paragraph \"Passing value types by reference\") here: value types in Dart, bu

4条回答
  •  盖世英雄少女心
    2020-12-01 18:25

    As dart is compiled into JavaScript, I tried something that works for JS, and guess what!? It worked for dart!

    Basically, what you can do is put your value inside an object, and then any changes made on that field value inside that function will change the value outside that function as well.

    Code (You can run this on dartpad.dev)

    main() {
      var a = {"b": false};
      
      print("Before passing: " + a["b"].toString());
      trial(a);
      print("After passing: " + a["b"].toString());
    }
    
    trial(param) {
      param["b"] = true;
    }
    

    Output

    Before passing: false
    After passing: true
    

提交回复
热议问题