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
Your problem is that objects are "pass by reference" in Dart (and mostly all languages).
digitsandlistOfDigitsare both instances of typeList. When you dolistOfDigits.add(digits), you are adding that same instance ofdigitsto the list every time. When you dodigits.clear(), you remove all the items inside it, and sincelistOfDigitsholds a reference to that same instance ofdigits, 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 cleardigits, you don't clear the one inside oflistOfDigits.You can do that by either using
List.fromor creating a new list fordigits.List.from:New list: