Flutter: Remove item for a list reflect another list

Issue

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_safetytrue

Solution

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;

Answered By – Hasan Mhd Amin

Leave a Comment