So i need to sort the elements by their date, so for an example if there are entries and 2 of them have the same date the result will be 3 in the result list.
Future<List<List<MoodData>>> moodData() async {
var result = await database
.ref()
.child("users/")
.child(user!.uid)
.child("moodData")
.once();
List<MoodData> x = [];
List<List<MoodData>> resultdata = [];
result.snapshot.children.forEach((element) {
maxID = int.parse(element.key.toString());
print(element.child("date").value);
if (x.length != 2) {
x.add(MoodData(
id: int.parse(element.key.toString()),
date: element.child("date").value.toString(),
moodValue: double.parse(element.child("y_value").value.toString()),
text: element.child("text").value.toString()));
} else {
resultdata.add(x);
x.clear();
}
});
print(resultdata);
return resultdata;
}
The problem is when I am then cleaning the list that got added to the resultdata the resultdata only has empty lists
CodePudding user response:
When you adding x
to resultdata
it not produces the copy of x
, x
just becomes an element of resultdata
.
Then you have 2 options for accessing x
data:
- Using given name
x
- Get it from
resultdata
by index
So when you call x.clear()
after resultdata.add(x)
it's the same as calling resultdata.last.clear()
.
The right solution is adding a copy of x
([...x]
) to resultdata
:
resultdata.add([...x]);
x.clear();