Flutter中_InternalLinkedHashMap转List类型错误的修复求助
修复Flutter类型不匹配异常:
_InternalLinkedHashMap<String, dynamic> 不是 List 的子类型 问题根源
API返回的是外层为Map的数据结构,其中destinations字段才是你需要的目的地列表,但代码直接把整个Map对象赋值给了List类型的destinationsList,导致类型不匹配抛出异常。
修复步骤
1. 修正数据获取逻辑
修改getAllDestinations函数,从返回的Map中提取destinations列表:
late String selectedDestination = ''; // 建议添加类型声明,提升代码安全性 late List<Map<String, dynamic>> destinationsList = []; var isLoaded = false; Future getAllDestinations() async { String urlDestinations = "http://localhost/api/destinations/"; var response = await http.get(Uri.parse(urlDestinations)); if(response.statusCode == 200){ var jsonData = json.decode(response.body); setState((){ // 提取Map中的destinations列表赋值给变量 destinationsList = jsonData['destinations']; isLoaded = true; }); } print(destinationsList); }
2. 修复下拉框冗余代码
下拉框中Text(item['name']).toString()属于冗余写法,直接使用Text(item['name'])即可:
// 结合加载状态避免空列表异常 isLoaded ? DropdownButtonFormField( decoration: InputDecoration( prefixIcon: const Icon( Icons.location_pin, color: primary, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), label: const Text( "Destination to *", style: TextStyle( fontSize: 16, color: primary, ), ), ), validator: (value) => value == null ? 'Field must not be empty' : null, isExpanded: true, value: selectedDestination, items: destinationsList.map((item) { return DropdownMenuItem( value: item['id'].toString(), // 移除冗余的Text嵌套和toString() child: Text(item['name']), ); }).toList(), onChanged: (String? value) { setState(() { selectedDestination = value!; }); }, ) : const CircularProgressIndicator()
内容的提问来源于stack exchange,提问作者Nz Mumbere
相关产品推荐
相关产品推荐

