39

I am trying to copy values of one list to another, I use three buttons 1st one to append a value to mylist, second one to clear the mylist, 3rd button to copy values from mynewlist to mylist.

i tried this

List<String> mylist = [
    'Albania',
    'Andorra',
    'Armenia',
    'Austria',
    'Azerbaijan',
    'Belarus',
    'Belgium',
    'Albania',
    'Andorra',
    'Armenia',
    'Austria',
    'Azerbaijan',
    'Belarus',
    'Belgium',
  ];

  List<String> mynewlist = [
    'Albania',
    'Andorra',
    'Armenia',
    'Austria',
    'Azerbaijan',
    'Belarus',
    'Belgium',
    'Albania',
    'Andorra',
    'Armenia',
    'Austria',
    'Azerbaijan',
    'Belarus',
    'Belgium',
  ];



Padding(
                padding: const EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: FlatButton(
                        onPressed: () {
                          setState(() {
                            print('clicked 1st');
                            print(mylist.length);
                            print(mynewlist.length);
                            mylist.add('sdsds');
                          });
                        },
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: FlatButton(
                        onPressed: () {
                          setState(() {
                            print('clicked 2nd');
                            print(mylist.length);
                            print(mynewlist.length);
//after i set mylist = mynewlist; when i click this button it clears the old and new list.
                            mylist.removeRange(0, mylist.length);
                          });
                        },
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: FlatButton(
                        onPressed: () {
                          setState(() {
                            print('clicked 3rd');
                            print(mylist.length);
                            print(mynewlist.length);
                         mylist = mynewlist;
                          });
                        },
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Image.asset(
                                'images/bulb.png',
                                width: 100,
                                height: 100,
                              ),
                              Text('bulb')
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              )


On the initial time it works perfectly the second time i click the second button it clears the mylist and mynewlist.

How can i copy the values of second list without clearing the new new list

Alvin John Babu
  • 1,710
  • 2
  • 16
  • 26

6 Answers6

80

Use myList = List.from(mynewlist); instead of mylist = mynewlist;

dKen
  • 3,078
  • 1
  • 28
  • 37
ibrahimkarahan
  • 2,697
  • 1
  • 9
  • 20
  • 3
    mylist = List.from(mynewlist); – YYY Oct 10 '20 at 04:40
  • Thank you :) and sorry for late reply :P – Alvin John Babu Dec 08 '20 at 16:42
  • Its weird but `streamDataListExtra = streamDataList;` works for me. – Kamlesh Jun 17 '21 at 20:00
  • 4
    @Kamlesh Yes, it might work for you, but you will not actually copy the value of the list. You only copied the pointer from the initial list. – Paul Sep 30 '21 at 10:51
  • 1
    This doesn't work with me because my list has sub-list, the main list it is cloned properly, but if i filter the sub-list the original list affected even when i use *myList = List.from(mynewlist);* any idea? – Osama Remlawi Oct 09 '21 at 21:40
  • @OsamaRemlawi for me, its affected just cloned list. https://jdoodle.com/ia/hVs – ibrahimkarahan Oct 11 '21 at 10:56
  • I've got the answer, and i liked to post it here as a reference for deep copy https://stackoverflow.com/questions/69514366/how-to-copy-complex-list-to-another-list-without-affecting-the-original-list-in – Osama Remlawi Oct 11 '21 at 12:29
13

Thats because you copied the object references (mylist = mynewlist) and not the content of the list. So after the first click, mylist has a reference to the same object in memory as mynewlist. So any operation on one of them, affect both.

To solve your problem you need to keep the object references intact and just copy around the contents of these lists.

enter image description here

Logemann
  • 2,767
  • 33
  • 53
11

use:

myNewList = [...myOldList]

it creates a shallow copy of items from myOldList to myNewList

for more information: you can search for 'spread operator in dart'.

Ahmed Fwela
  • 955
  • 1
  • 13
  • 32
habeshacoder
  • 109
  • 1
  • 5
9

var YOURCOPY = YOURLIST.map((v) => v).toList();

dKen
  • 3,078
  • 1
  • 28
  • 37
Johan Witters
  • 1,529
  • 11
  • 23
4

Deep copy of a custom class List

If you have a list of classes, make sure to clone/copy each class. Otherwise, if you change objects in the original list, it will also change in the new one. Here is one way to prevent it:

  1. Add a clone() function to your class

    class RandomObject {
    
    RandomObject(this.x, this.y);
    
    //add clone function to your class:
    RandomObject.clone(RandomObject randomObject): this(randomObject.x, randomObject.y);
    
    int x;
    int y;
    }
    
  2. To copy, map through each element and clone it

    final List<RandomObject> original = [RandomObject(1, 2), RandomObject(3, 4)];
    
    final List<RandomObject> copy = original.map((v) => RandomObject.clone(v)).toList();
    
Paul
  • 1,349
  • 1
  • 14
  • 26
  • 1
    Source inspired: [deep copy object](https://stackoverflow.com/a/54136662/11003497) – Paul Sep 30 '21 at 16:18
1

You can also call method:toList() on any iterables (in this case List) which you want to create a copy of and not a reference.

Atul Singh
  • 21
  • 3