Home > database >  how to copy list of models to new list in flutter?
how to copy list of models to new list in flutter?

Time:12-23

I am facing an issue where I cant copy a list of models to new list with an easy way.

What I want to achieve is:

List<Package> event_packages = [...]; // list with data here
List<Package> packages = List.from(event_packages);

The issue now is whenever I edit some data in the packages, event packages get edited too. I believe because it copies the object references.

Solution so far is:

List<Package> packages = [];
event_packages.forEach((package) { 
   packages.add(Package.fromJson(jsonDecode(jsonEncode(package))));
});

But seems very hacky and slow.

What is the right way to do this?

CodePudding user response:

Sadly I don't believe there is a simple method to do what you want, what I recommend is making a constructor that copies the data from one package to another but depending on what exactly package is, that might be not possible?

class Package {

  Package({this.title='', this.age=0, this.height=0});

  Stirng title;
  int age
  double height;

  // here
  factory Package.fromPackage(Package other) {
    return Package(title: other.title, age: other.age, height: other.height);
  }
}

Then when making the second list:

List<Package> event_packages = [...]; // list with data here
List<Package> packages = event_packages.map((pckg) => Package.fromPackage(pckg)).toList();

CodePudding user response:

You can copy a new List with the following code:

List<Package> event_packages = [...]; // list with data here
List<Package> packages = [];
packages.addAll(event_packages);
  • Related