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:
- 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. - Wrong Entity Reference: You accidentally used
UserResponsein yourmapcall instead ofFineResponse—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
相关产品推荐
相关产品推荐

