'Casting DatabaseEvent snapshot.value to a specific type in Flutter
I'm trying to retrieve data from a DatabaseEvent event type. The data I have on the database is this in this layout
Basically some users id and each user has a a different number of menu orders. What I want to do is retrieve each order of each user and do something with it.
Right now I'm using
Map data = event.snapshot.value as Map;
but since it's a dynamic cast, it sometimes retrieves the values as a List of Objects and sometimes as a Map of Objects..
For example if the orders number are in order as the picture above (order number 1 and number 2), it retrieves the data like this :
{ZqsrXaqhXbPFgPTvIbnxRNw3bX42: [null, {number: 1, quantity: 3}], tzqjzgzy: [null, {number: 1, quantity: 2}, {number: 2, quantity: 3}]}
as a List and it retrieves a null because there is no order 0. If I change the orders from 1 and 2 to 2 and 3, it gives me the same result but with two nulls at the beginning.
If I change the orders number to more random numbers, it retrieves them correctly as a Map, or more specifically as an _InternalLinkedHashMap<Object?, Object?>.
{ZqsrXaqhXbPFgPTvIbnxRNw3bX42: {12: {number: 12, quantity: 2}, 24: {number: 24, quantity: 3}}}
I want to retrieve it everytime in the same way so I tried casting the snapshot.value in different ways like so
Map<dynamic, Map> data =
event.snapshot.value as Map<dynamic, Map>;
but everytime I do I don't get any data.
This is my code right now
.then((DatabaseEvent event) {
if (event.snapshot.exists) {
Map<dynamic, dynamic> data =
event.snapshot.value as Map;
//sum all orders
Map<int, Map> allOrders = {};
data.forEach((key, userOrders) {
userOrders.forEach((key, order) {
allOrders[order['number']] = {
'number': order['number'],
'quantity': allOrders[order['number']] != null
? allOrders[order['number']]!['quantity'] +
order['quantity']
: 0 + order['quantity'],
};
});
});
return allOrders;
} else {
throw Exception('Error snapshot does not exist');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|