Matthias
Matthias

Reputation: 4163

Runtime type checking in Dart - Check for List

I want to check if the response of a http request matches a specific datatype (= List<dynamic).

case 200:
    var responseJson = json.decode(response.body);

    print(responseJson['results'].runtimeType);  // Output: I/flutter (13862): List<dynamic>
    print(responseJson['results'].runtimeType is List<dynamic>);  // Output: I/flutter (13862): false

    if (responseJson['results'].runtimeType is List<dynamic> &&
        responseJson['results'].length > 0) {
      return responseJson;
    }
    throw NotFoundException('Result is empty...');

I'm confused... why does it print false? The ouput of runtimType shows List<dynamic>so it should be true...

Upvotes: 2

Views: 2298

Answers (1)

julemand101
julemand101

Reputation: 31209

You should only use runtimeType for debug purposes since this property returns the actual type of the object on runtime and cannot be used for checking if a given type is compatible with another type.

The is operator is the correct operator you are using for checking the type but you are using it against runtimeType which returns a Type object. Instead you should just use it like: responseJson['results'] is List<dynamic>.

This will check if the type is compatible with List<dynamic>. You could also do it like this which is a little simpler: responseJson['results'] is List

Upvotes: 7

Related Questions