Flutter中_InternalLinkedHashMap与List类型不匹配错误求助
类型不匹配错误修复方案
错误根源:
你把接口返回的整个JSON对象(_InternalLinkedHashMap类型)直接赋值给了List类型变量,导致类型不匹配。接口返回的JSON是一个包含status、total、dictionary_terms的对象,而你需要的化合物列表在dictionary_terms.compound路径下,且列表里的每个元素是字符串,不是带compound字段的对象。修复后的代码:
import 'dart:convert'; import 'package:http/http.dart' as http; class SugCompound { final String compound; const SugCompound({ required this.compound, }); // 接口返回的是字符串,直接用字符串创建实例即可 static SugCompound fromString(String compound) => SugCompound( compound: compound, ); } class SugCompoundApi { static Future<List<SugCompound>> getSugCompoundSuggestions(String query) async { final url = Uri.parse( 'https://website.com/rest/autocomplete/compound/$query/json?limit=6'); final response = await http.get(url); if (response.statusCode == 200) { // 先解码成Map类型,匹配接口返回的JSON结构 final Map<String, dynamic> responseData = json.decode(response.body); // 取出化合物字符串列表,确保类型安全 final List<String> compoundStrings = List<String>.from( responseData['dictionary_terms']['compound'], ); return compoundStrings .map((compound) => SugCompound.fromString(compound)) .where((sugCompound) { final compoundLower = sugCompound.compound.toLowerCase(); final queryLower = query.toLowerCase(); return compoundLower.contains(queryLower); }).toList(); } else { throw Exception('Failed to load suggestions'); } } }
- 关键修改说明:
- 将
json.decode(response.body)的结果赋值给Map<String, dynamic>类型变量,符合接口返回的JSON结构。 - 通过
responseData['dictionary_terms']['compound']正确取出化合物列表,并用List<String>.from()确保类型安全。 - 修改
SugCompound的转换方法为fromString,因为每个列表元素直接是化合物名称字符串,无需从Map中提取字段。
- 将
内容的提问来源于stack exchange,提问作者SherriB
相关产品推荐
相关产品推荐

