I have the two variables in my code. I wish to re-use the first variable after updating the second variable with the data. However, when I clear the first variable, the data in the second variable also gets cleared.
Below is my code: (I have simplified the code to get the issue across)
class DataScreen extends StatefulWidget {
final Users user;
const DataScreen({Key? key, required this.user}) : super(key: key);
@override
State<DataScreen> createState() => _DataScreenState();
}
class _DataScreenState extends State<DataScreen> {
List<double> divTemp= []
List<Map<String, Map<String, List<dynamic>>>> divData = [];
@override
void initState() {
// TODO: implement initState
super.initState();
future = _future();
}
Future<int> _future() async {
var step1 = await _getDivData();
if (step1 == 0) {
Get.to(() => ChartViewThree(user: widget.user, divdata: divData));
}
return 0;
}
Future<int> _getDivData() async {
for(int i = 0; i< 10; i++){
divTemp.add(i);
}
divData.addAll([{'D01': {"Deg": divTemp}}]);
divTemp.clear();
for(int i = 0; i< 10; i++){
divTemp.add(i+1);
}
divData.addAll([{'D02': {"Deg": divTemp}}]);
}
}
When I use divTemp.clear(), the data in divData is also cleared. I do not wish to create a temp variable for every loop, hence would like to re-use divTemp again.
After this of course I have the build Widget which I am not showing here for keeping the focus on the issue.
Any comments on this is welcome.
>Solution :
When you pass divTemp to other variable, you are passing the reference to the original list, so the value that correspond to the "Deg" key inside divData still refers to the same list as the one that the divTemp variable refers.
There are several ways to copy a list, one way is to use the spread operator:
[...divTemp]
This will do a shallow copy, but is sufficient for your case since the element type is double.
So the line would be:
divData.addAll([{'D01': {"Deg": [...divTemp]}}]);
This way, [...divTemp] will create a totally new list, so operations applied to divTemp won’t affect this new list.
See also: