我收到错误消息:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Future <dynamic>`
_LocationScreenState.build.<anonymous closure>
(package:clima/screens/location_screen.dart:71:32)
<asynchronous suspension>
精确定位的行在其中:
FlatButton(
onPressed: () async {
var weatherData = await weather.getLocationWeather();
updateUI(weatherData); //<==it's this line
},
weather.getLocationWeather()
返回类型为Future<dynamic>.
的变量,它是JSON,在调试器中对其求值,它是预期的JSON。 upDateUI()
方法开始
void updateUI(Future<dynamic> weatherDataFuture) async {
final weatherData = await weatherDataFuture;
,然后继续分析所得的weatherData。它在程序的前面被调用,并且按预期工作。我敢肯定,这个问题与我永无止境但仍在继续努力理解异步编程有关:-)
答案 0 :(得分:2)
await weather.getLocationWeather()
得到getLocationWeather
返回的未来,并等待其完成一个值。该值是一张地图。
然后,您将使用该映射值调用updateUI
,即使它期望将来也是如此。该变量的类型为dynamic
,因此您不会收到任何静态警告,而只会收到运行时错误。
onPressed: () async {
var weatherData = await weather.getLocationWeather();
updateUI(weatherData); //<==it's this line
尝试删除await
。这样weatherData
将是Future<dynamic>
,它恰好是updateUI
期望的类型。 (然后,您还可以从函数中删除async
。)
答案 1 :(得分:0)
尝试一下:
final weatherData;
Future<Map<String, dynamic>> weatherDataFuture async{
return weather.getLocationWeather();
}
FlatButton(
onPressed: () {
weatherDataFuture.then((value){
weatherData=value.values;
});
}
)
答案 2 :(得分:0)
获取数据的返回值需要强制转换。我建议您查阅flutter文档中的JSON教程。
FlatButton(
onPressed: () async {
var weatherData = Map<String, dynamic>.from(await weather.getLocationWeather());
updateUI(weatherData); //<==it's this line
},
void updateUI(Map<String, dynamic> weatherData) async {
...
=====根据评论进行编辑=====
FlatButton(
onPressed: () async {
var weatherData = SynchronousFuture(Map<String, dynamic>.from(await weather.getLocationWeather()));
updateUI(weatherData); //<==it's this line
},
void updateUI(Future<Map<String, dynamic>> weatherData) async {
...