I need to cast a List and a Map of unknown types to specific types. If the List or Map are not empty all is well. But if they are ever empty I get a cast error.
When list is empty:
final list = [];
final result = list as List<Map<String, dynamic>?>;
Output
type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>?>' in type cast
When Map is empty:
final map = {};
final result = map as Map<String, dynamic>;
Output
type '_Map<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast
For context: I’m fetching data from firebase. The DocumentSnaphot.data()
of the firebase package returns an Object?
. Therefore I have no control over what type the data is. Hence the casting…
2
Answers
For casting lists you should use
List<T>.from(list as List)
,List.cast
orList.castFrom
.For casting maps you should use
Map<T>.from(map as Map)
orMap.castFrom
.(I answered my own question)
You can use pattern matching to respond to the different types returned by Firebase.
Here’s an example:
You can then use the
parseData
function to parse your Firebase data:Dart also provides the
is
operator to first check if some reference is of a certain type: