Home > other >  Passing An Object Instance By Value In Dart
Passing An Object Instance By Value In Dart

Time:11-20

I have an object that was created with GetxController and it has a list field. I want to select a specific item in that list and change some parameters. But I should be able to cancel this changing scenario. Because when I select an item and change it, also change that class list item.

In Dart, objects pass by reference. But I need to pass it by value for canceling change. There's any way to pass an object instance by value?

CodePudding user response:

No.

But you can just make a copy yourself and pass that. And depending on whether the change was confirmed you can eiter copy it back into your list or not.

CodePudding user response:

In this kind of scenario, you should try to use immutable types. There are good Dart libraries for that, even if the language doesn't have native support for it... with truly immutable data types, you essentially get pass-by-value semantics. They also make it easy to make copies of your data with small modifications on the returned value (while the original obviously remains unmodified).

Example packages you could use:

  • Related