Search code examples
flutterlistarrayliststateful

Flutter add List<int> to List<List>


I have statefull widget, I want to create list of number and then ad them aslist onanother list,

I initialize the list ` late List digits; late List listOfDigits;

  @override
  void initState() {
    digits = [];
     listOfDigits = [];
    super.initState();
}`

I have textfiled with controller name = number, and button to add the number to digits list : digits.add(int.parse(number.text)); setState(() {});

and another button to add digits list to listOfDigits and clear digits list:

    listOfDigits.add(digits)
    digits.clear();
    setState(() {});

firs time create list of digits I get : [[]] when I create second digis like [1,8,-9] I get : [[1,8,-9]] for thisrd time any digit (for example 7) add to digits it add otamitcly to both list and be like this : [[1,8,-9,7],[1,8,-9,7]]

I tried same thing with provider I get same result


Solution

  • Your problem is that objects are "pass by reference" in Dart (and mostly all languages).

    digits and listOfDigits are both instances of type List. When you do listOfDigits.add(digits), you are adding that same instance of digits to the list every time. When you do digits.clear(), you remove all the items inside it, and since listOfDigits holds a reference to that same instance of digits, it is empty too.

    What you can do to fix that is to create a copy (a new instance) of the list of integers and pass that to the listOfDigits, so that when you clear digits, you don't clear the one inside of listOfDigits.

    You can do that by either using List.from or creating a new list for digits.

    List.from:

    // List.from creates a new list with the same values as `digits`.
    listOfDigits.add(List.from(digits)); 
    digits.clear();
    setState(() {});
    

    New list:

    listOfDigits.add(digits);
    // Here, instead of clearing the same list inside `listOfDigits`,
    // you are simply creating a new one for that variable (and keeping
    // the old instance unmodified).
    digits = [];
    setState(() {});