Flutter API调用出现NoSuchMethodError异常求助
问题分析与解决方案
这个错误的核心原因很明确:你调用的OpenWeatherMap weather?q=ferentino接口返回的是单个天气对象,而非数组,但你却尝试用数组的map方法去遍历它,导致了NoSuchMethodError(因为单个_InternalLinkedHashMap没有你期望的List类型的map方法)。
具体修正步骤:
调整API调用后的对象转换逻辑
原代码中你试图把resJson(单个Map对象)当成数组来处理,直接改为创建单个Meteo实例即可:Future ferentinoGet() async { var dio = Dio(); Response response = await dio.get('https://api.openweathermap.org/data/2.5/weather?q=ferentino&appid=****************'); final resJson = response.data; // 移除map遍历,直接用fromMap创建单个实例 datiFerentino = Meteo.fromMap(resJson); print(response.data); }修正
datiFerentino的类型定义
如果你之前把datiFerentino定义为List<Meteo>,现在需要改成单个对象类型(建议加上可空修饰符处理空值情况):Meteo? datiFerentino;优化
Meteo.fromMap构造函数的类型安全性
为了避免潜在的类型转换错误,建议给字段加上明确的类型转换:class Meteo { int id; double temperatura; String name; Meteo(this.id, this.temperatura, this.name); Meteo.fromMap(Map<String, dynamic> mappa){ this.id = mappa['id'] as int; // 处理temp可能是int的情况,转为double this.temperatura = (mappa['main']['temp'] as num).toDouble(); this.name = mappa['name'] as String; } }
为什么原代码会报错?
你调用的map方法是List类的方法,用于遍历数组元素并转换类型;而API返回的是单个Map对象,它的map方法签名是map<K2, V2>((K, V) => MapEntry<K2, V2>) => Map<K2, V2>,作用是转换键值对,和你期望的List.map完全不同,所以触发了NoSuchMethodError。
内容的提问来源于stack exchange,提问作者amepro
相关产品推荐
相关产品推荐

