You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter新手:Get请求出现'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'错误,如何修改Get方法?

Hey there! Let's break down what's causing your error and fix it step by step.

What's Going Wrong?

Your error 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' happens for two key reasons:

  1. Nested List Structure: Your API returns a double-nested array (List<List<dynamic>>), but your code is treating the entire response as a single-level list of objects. Look at your Postman response: the actual fine objects are wrapped inside another list, which is itself inside the top-level list.
  2. Wrong Entity Reference: You accidentally used UserResponse in your map call instead of FineResponse—that's a simple typo but adds to the type mismatch issue.

Fixed Code for Your getAll Method

Here's the corrected version with explanations:

Future<List<FineResponse>> getAll(String apiToken) async {
  try {
    Response response = await _dio.get(
      apiEndpoint + "fines",
      options: Options(headers: {"Authorization": apiToken}),
    );

    // 1. Access the inner list that contains your fine objects
    //    (response.data is the top-level list, we take its first element)
    final List<dynamic> fineDataList = response.data[0] as List<dynamic>;
    
    // 2. Map the inner list to FineResponse objects (fixed the UserResponse typo)
    return fineDataList
        .map<FineResponse>((element) => FineResponse.fromJson(element))
        .toList();
  } catch (error, stacktrace) {
    // Better error handling than returning null—print details and throw/return empty list
    print('Error fetching fines: $error\nStacktrace: $stacktrace');
    // Choose one: throw to let the caller handle, or return empty list
    throw Exception('Failed to load fines');
    // return [];
  }
}

Optional: Add Safety Checks

If there's a chance the API could return an empty top-level list, add a guard clause to avoid index-out-of-bounds errors:

if (response.data is List && response.data.isNotEmpty) {
  final List<dynamic> fineDataList = response.data[0] as List<dynamic>;
  return fineDataList.map<FineResponse>((el) => FineResponse.fromJson(el)).toList();
} else {
  return []; // Or throw an error if empty response is unexpected
}

内容的提问来源于stack exchange,提问作者morris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:57:31