'Casting an Object as a Map when Firebase RTDB is updated
I'm doing a query in Firebase RTDB as follows:
Future<UsuarioModel> cargarUsuarioEmpresa(String idEmpresa, String idUsuario) async {
UsuarioModel _usuario = UsuarioModel();
Query resp = db.child('PATH/usuarios/$idUsuario');
final snapshot = await resp.once();
_usuario = UsuarioModel.fromJson(Map<String, dynamic>.from(snapshot.value));
return _usuario;
}
It was working perfect until I upgraded firebase_database package from 8.0.1 to 9.0.3
Now, I have an error
The getter 'value' isn't defined for the type 'DatabaseEvent'.
Then, I updated my method to receive a DatabaseEvent:
final event = await resp.once();
_usuario = UsuarioModel.fromJson(Map<String, dynamic>.from(event.snapshot.value));
But an error appears:
The argument type 'Object?' can't be assigned to the parameter type 'Map<dynamic, dynamic>'.
I tried to add an as casting:
_usuario = UsuarioModel.fromJson(Map<String, dynamic>.from(event.snapshot.value as Map<String,dynamic>));
but It doesn't work. I get an error after build:
Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' in type cast
How can I cast properly a Map of Objects as a Map<String, dynamic> to fix the error?
Solution 1:[1]
Due to changes in version 9 from dynamic to object, you can define the snapshot value as dynamic:
final event = await resp.once();
_usuario = UsuarioModel.fromJson(Map<String, dynamic>.from(event.snapshot.value as dynamic));
It's a workaround, but it does work!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David L |
