Flutter: Remove item for a list reflect another list

Viewed 946

I have the following flutter code, I have a list, let's call it list1, and I am coping the value of this list to another list list2.

When I remove an element from list1, it's automatically removed from list2!

There is a minimal code that reproduce the issue. I couldn't understand this strange behavior, could someone explain it to me?

What I want to do is remove an item form list1 but keep list2 as it is.

This is the code:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(EmptyFile());

class EmptyFile extends StatefulWidget {
  final list1 = ["1", "2", "3"];
  EmptyFile({Key? key}) : super(key: key);
  @override
  _EmptyFileState createState() => _EmptyFileState(list1);
}

class _EmptyFileState extends State<EmptyFile> {
  List<String> list1 ;
  List<String> list2 = [];

  _EmptyFileState(this.list1) {
    list2 = list1;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Example App'),
            ),
            body:
            Container(
              child: RaisedButton(
                onPressed: () {
                  print("list1.last ${list1.last}"); // the result is: list1.last 3
                  list2.remove("3");                 // here I delete from list2 (list TWO)
                  print("list1.last ${list1.last}"); // the result is: list1.last 2 . Here an item from list ONE has been deleted!!!
                },
                child: Text('delete last Item'),
              ),
            )
        ));
  }
}


You can run the code online from here: https://dartpad.dev/81d0a66ac7c46258df7847fdc7a10e96?null_safety=true

3 Answers

Apparently, dart copy the lists by reference. So, to copy the values of a list to another list, use the following code:

list2  = List.from(list1);

instead of:

list2 = list1;

By this

list2 = list1;

you are not actually making a copy of list1. It is the same list being assigned to list2 too.

So you need to change to this.

list2 = [...list1];

You can use spread operation:

list2 = [...list1];

That should allow any iterable to copy the values instead of using the reference.

Related