I'm trying to list a realtime database. I have the problem that the way of data are mapped, but i'm not understand how to solve.
My code is:
Future<List<ProductoLeido>> getProductosEnGia() async {
List<ProductoLeido> prdEnGia = [];
try {
DatabaseEvent event =
await FirebaseDatabase.instance.ref().child('ProductosEnGIA').once();
if (event.snapshot.exists) {
DataSnapshot s = event.snapshot;
print("out forEach");
Map<String, Object?>.from(s.value as dynamic).forEach((key, value) => {
print('key:' key),
print("in forEach"),
});
}
return prdEnGia;
} catch (e) {
return prdEnGia;
}
}
And the returned is:
TypeErrorImpl (Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'List')
I'm attach image to share more data in debug mode.
CodePudding user response:
I made a output of snapshot value, and the results is:
CodePudding user response:
It looks like the data you're reading has sequential, numeric keys, which means that the Firebase SDK maps it to an array/list and not to a map.
So instead of:
Map<String, Object?>.from(s.value as dynamic)
You'll want to use:
List<Object?>.from(s.value as dynamic)
I recommend reading this blog post to learn more about how Firebase handles arrays: Best Practices: Arrays in Firebase.
CodePudding user response:
Done. I solve the problem. That is the solution:
Future<List<ProductoLeido>> getProductosEnGia() async {
List<ProductoLeido> prdEnGia = [];
try {
DatabaseEvent event =
await FirebaseDatabase.instance.ref().child('ProductosEnGIA').once();
if (event.snapshot.exists) {
DataSnapshot s = event.snapshot;
final m = s.value as List<dynamic>;
for (int i = 0; i < m.length; i ) {
final p = ProductoLeido.fromJson(m[i]);
print(m[i].toString());
Map<dynamic, dynamic> d = m[i];
ProductoLeido.fromJson(d);
var cod = ProductoLeido.fromJson(d).codigo;
var cant = ProductoLeido.fromJson(d).cantidad;
print('CODIGO>>>>' cod.toString());
ProductoLeido prL = ProductoLeido(cod, cant);
prdEnGia.add(prL);
}
}
return prdEnGia;
} catch (e) {
return prdEnGia;
}
}