I encountered a TypeError with data received from an API. To simulate the issue clearly, I have provided a code example below:
//This is mock data to simulate the API.
//The length of the array or the keys is not specified
// We only know that it should be a List<Map<String, dynamic>>
List<dynamic> dat2 = [{"id1": 'food',},{'id2': "car"}];
var data = {"types": dat2, "clientId": "Id"}
;
the code:
if (data case {
//how I can cast it to List<Map<String, dynamic>> here without extra code?
"types": List<Map<String, dynamic>> types,
"clientId": String clientId})
{
debugPrint('types:$types, clientId: $clientId');
} else {
debugPrint('Error');
}
The error occurs within the "types" argument. How can I cast it appropriately within the if condition to resolve this?
3
Answers
Try this!
If it’s helpful to you, then accept the answer and don’t forget to upvote.
In the first line you declare that
dat2
is of typeList<dynamic>
which does not match the more specificList<Map<String, dynamic>>
.It would work by declaring
dat2
as:Running the program results in the following output:
If
dat2
has to be of typeList<dynamic>
then you will have to use the same type in the pattern:If you really want to do this with pattern matching, I think you have to do it in two stages. I got this to act as expected, hopefully it can be a starting point for you:
This outputs
(food, car, Id)
.