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

执行await http.get(url)后程序跳出_loadPrices函数的技术求助

问题根源分析
  1. 异步调用未等待:login()中调用_loadPrices(salesmanData)时未添加await关键字,程序会直接跳过异步HTTP请求,立即执行后续的列表检查逻辑。此时SAP接口的响应还未返回,priceListNotifier必然为空,触发错误弹窗。
  2. 数据重复累加:第二次登录时,第一次触发的异步请求可能已经完成并将数据存入priceListNotifier,第二次调用_loadPrices会再次向通知器中添加新数据,最终导致列表数据翻倍。
  3. 语法错误:_loadPrices中Uri.parse的括号未闭合,会导致代码编译失败,需先修复该问题。
修复方案及代码修正

1. 等待异步请求完成

在login()中调用_loadPrices时添加await,确保价格数据加载完成后再执行后续逻辑:

await _loadPrices(salesmanData);
final loadedPriceList = ref.read(priceListNotifier);

if (loadedPriceList.isEmpty) {
  _showErrorDialog('Failed to load Prices');
  return;
}

2. 避免数据重复

在向priceListNotifier添加新数据前,先清空旧数据。如果你的通知器没有内置清空方法,需在priceListNotifier中实现:

// 假设priceListNotifier是StateNotifier<List<PriceList>>
void clearPrices() {
  state = [];
}

然后在_loadPrices中调用清空方法后再添加新数据:

Future<void> _loadPrices(salesMan) async {
  // 修复Uri.parse的闭合括号
  final url = Uri.parse(
      'http://1XX.XX.XX.XXX:9000/sap/ZSD_VS_DEMO_SRV/CSP_PricingSet?\$format=json&\$filter=KUNNR eq \'${salesMan.userId}\'');
  final List<PriceList> loadedPriceList = [];

  try {
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final Map<String, dynamic> responseData = json.decode(response.body);
      
      // 转换responseData为loadedPriceList的逻辑代码

      // 先清空旧数据,再添加新数据
      ref.read(priceListNotifier.notifier).clearPrices();
      ref.read(priceListNotifier.notifier).addPrices(loadedPriceList);
    } else {
      throw Exception('SAP接口返回错误: ${response.statusCode}');
    }
  } catch (e) {
    print('加载价格列表失败: $e');
    rethrow; // 抛出异常让上层login逻辑处理
  }
}

3. 完善错误处理

在login()中添加异常捕获,处理网络请求失败或接口错误的情况:

try {
  await _loadPrices(salesmanData);
  final loadedPriceList = ref.read(priceListNotifier);
  
  if (loadedPriceList.isEmpty) {
    _showErrorDialog('加载价格列表失败');
    return;
  }
  
  // 登录成功后的逻辑,例如跳转至主页
} catch (e) {
  _showErrorDialog('加载价格列表失败: $e');
}

内容的提问来源于stack exchange,提问作者Ajeeth ram

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:13:14