Search code examples
jsonflutterflutter-http

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'


I'm struggling to see how these type errors could be resolved in Flutter.

I am making an HTTP request to a server which responds with the following JSON:

{
  "message": "The given data was invalid.",
  "errors": {
    "email": ["Email is required"]
  }
}

I am assigning the data from the response like so:

Future login(String email, String password) async {
    ...
    Map<String, dynamic> data = json.decode(response.body);

    final List<String> emailErrors = data['errors']['email'];
    final List<String> passwordErrors = data['errors']['password'];
}

Once I try to do that I get the following error:

Unhandled Exception: type 'List' is not a subtype of type 'List'

It seems like using type dynamic it will pretty much throw an error if you try to set a type annotation afterwards for any type. How can this be solved?


Solution

  • You get this error because the data['errors']['email']returns a List<dynamic>.

    You have to cast items to String like that :

    final List<String> emailErrors = data['errors']['email'].cast<String>()