How to cast dynamic to T or List<T>

Viewed 117

I have a service to call api and some methods expects just Object and the rest expects list of objects. And I'm trying some tricks with generics but then errors in _get method with casting occurs.

// List
  Future<List<ToDo>> getToDos() async {
    final List<Map<String, dynamic>> response =
        await _get<List<Map<String, dynamic>>>(url: "ToDos");

    final List<ToDo> result =
        response.map((data) => ToDo.fromJson(data)).toList();
    return result;

//Object
  Future<ToDo> getToDo() async {
    final Map<String, dynamic> response =
        await _get<Map<String, dynamic>>(url: "ToDo");

    final ToDo result = ToDo.fromJson(response);
    return result;
  }
  Future<T> _get<T>({
    required String url,
  }) async {
    final Response response = await get(
      Uri.https(_apiURL, url),
    );

    if (response.statusCode == 200) {
      final T jsonResponse = json.decode(response.body) as T;
      return jsonResponse;
    } else {
      throw Exception(response.body);
    }
  }

Error:

Exception has occurred. _CastError (type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast)

Is it even possible to solve it like I'm trying?

[Update]:

Solution:

  Future<T> _get<T, K>({
    required String url,
  }) async {
      final Response response = await get(
        Uri.https(_apiURL, url),
      );

      if (response.statusCode == 200) {
        final dynamic jsonResponse = json.decode(response.body);
        if (jsonResponse is List) {
          return List<K>.from(jsonResponse) as T;
        } else {
          return jsonResponse as T;
        }
      } else {
        throw Exception(response.body);
      }
  }
1 Answers

There's a list function called cast. You can cast a dynamic list to List<Map<String, dynamic>> like this:

final aList=[]//your list;
final castedList=aList.cast<Map<String, dynamic>>();
Related