You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用http包出现Unawaited异步帧表达式评估错误求助

问题解决:Flutter天气API请求崩溃及异常处理优化

问题代码

import 'package:weather_app/models/constants.dart';
import 'package:weather_app/models/weather.dart';
import 'package:http/http.dart' as http;

dynamic weatherData(String location) async {
    var url = Uri.parse(searchWeatherAPI(key: Constants.API_KEY) + location);

    var response = await http.get(url); // this is line 30

    if (response.statusCode == 200) {
      List<Weather> weatherData = weatherFromJson("[${response.body}]");
      return weatherData;
    } else {
      print(response.body);
      return response.body;
    }
}

调试错误信息

ChromeProxyService: Failed to evaluate expression 'see': InternalError: Expression evaluation in async frames is not supported. No frame with index 30..

ChromeProxyService: Failed to evaluate expression 'only': InternalError: Expression evaluation in async frames is not supported. No frame with index 30..

ChromeProxyService: Failed to evaluate expression 'unawaited': InternalError: Expression evaluation in async frames is not supported. No frame with index 30..

ChromeProxyService: Failed to evaluate expression 'the': InternalError: Expression evaluation in async frames is not supported. No frame with index 30..

解决方案

1. 调试器错误处理(非代码逻辑问题)

上述错误是Chrome调试器的限制,无法在异步帧中执行表达式求值,和代码逻辑无关。解决方式:

  • 不要在await http.get(url)行设置断点,将断点移至if (response.statusCode == 200)分支内或函数其他同步代码段。
  • 改用Flutter DevTools进行调试,对异步代码的支持更完善。
  • 升级Flutter SDK至最新稳定版,部分旧版本存在该调试器bug。

2. 完善异常捕获与业务逻辑

原try/catch未生效是因为未覆盖完整执行流程,修改代码如下,确保捕获所有异常并统一返回格式:

import 'package:weather_app/models/constants.dart';
import 'package:weather_app/models/weather.dart';
import 'package:http/http.dart' as http;

Future<Object> weatherData(String location) async {
  try {
    var url = Uri.parse(searchWeatherAPI(key: Constants.API_KEY) + location);
    var response = await http.get(url);

    if (response.statusCode == 200) {
      List<Weather> weatherData = weatherFromJson("[${response.body}]");
      return weatherData;
    } else {
      // 返回API提供的位置不存在提示
      return response.body.trim();
    }
  } catch (e) {
    // 捕获网络异常、JSON解析异常等所有错误,返回友好提示
    return "请求失败:${e.toString()}";
  }
}

3. 调用端处理逻辑

调用该函数时,通过类型判断区分返回结果:

void fetchWeather(String location) async {
  var result = await weatherData(location);
  if (result is List<Weather>) {
    // 显示天气数据
    print("天气数据:${result.first.cityName}");
  } else if (result is String) {
    // 显示错误提示给用户
    print("提示:$result");
  }
}

内容的提问来源于stack exchange,提问作者Yousef Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 05:36:22