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

Flutter请求API渲染数据时出现空值检查运算符空值报错

Flutter货币选择器数据渲染空报错修复

问题根因

  • 选中回调未更新请求参数:货币选择器onSelect回调返回了选中的Currency实例,但代码未将选中的币种编码赋值给请求依赖的currencyType变量,导致请求携带的币种参数错误,接口返回的数据中bank字段为空
  • 重复触发数据请求:onSelect回调中在setState内、外各调用了一次fetchData(),单次选择会触发两次无效请求
  • 缺失空值防护:组件首次渲染、请求加载中、请求失败的场景下,getBankInfo或其内部的bank属性为null,直接使用!强制非空解包就会触发Null check operator used on a null value报错
  • 接口路径不一致:预期请求路径为wwww.fetchrecordbasedoncurrency?curr=${selectedCurrency},实际代码请求的是fetch-data.php?curr=${currencyType},若后端未做路径映射会返回不符合预期的结构
  • 序列化逻辑风险:若BankInfo.fromJson方法中字段映射和接口返回的JSON key不匹配,也会导致解析后的bank属性为null

修复方案

  1. 修正货币选择器选中逻辑,赋值选中币种、移除重复请求
ElevatedButton(
  onPressed: () {
    Navigator.pop(context);
    showCurrencyPicker(
      context: context,
      showFlag: true,
      showSearchField: true,
      showCurrencyName: true,
      showCurrencyCode: true,
      onSelect: (Currency currency) {
        setState(() {
          // 把选中的币种编码赋值给请求参数变量
          currencyType = currency.code;
        });
        // 参数更新完成后再触发请求,仅调用一次
        fetchData();
      },
      currencyFilter: <String>[
        'AUD',
        'CAD',
        'EUR',
        'USD'
      ],
      favorite: ['USD'],
    );
  },
  child: const Text('Select Payment Currency'),
)
  1. 优化数据拉取方法,增加合法性校验,核对接口路径
// 变量声明时不要滥用late,允许空值并设置合理默认值
BankInfo? getBankInfo;
String currencyType = 'USD'; // 默认值和选择器默认收藏项保持一致
bool isLoading = false;

void fetchData() async {
  try {
    setState(() {
      isLoading = true;
    });
    // 核对接口路径,和后端提供的地址保持一致
    final response = await networkHandler.get(
        '${networkHandler.url}fetch-data.php?curr=$currencyType');
    // 校验返回结构合法性后再做模型转换
    if (response != null && response['bank'] != null) {
      getBankInfo = BankInfo.fromJson(response);
      print("Bank Currency: ${getBankInfo?.bank?.currency}");
    }
  } catch (ex) {
    print({ex, 'An error occured while fetching bank data'});
  } finally {
    setState(() {
      isLoading = false;
    });
  }
}
  1. 优化组件渲染逻辑,增加加载态和空态处理,避免强制解包
// 对应位置的渲染组件
Widget buildBankInfo() {
  if (isLoading) {
    return const CircularProgressIndicator();
  }
  if (getBankInfo?.bank == null) {
    return const Text('未查询到对应币种的银行记录');
  }
  return Text(getBankInfo!.bank!.name);
}

若上述修改后仍报错,检查BankInfo.fromJson的序列化逻辑,确认模型字段和接口返回的JSON key完全匹配,无拼写、大小写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:39:16