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

Flutter Radio Button报错:int?无法赋值给int类型变量

Flutter Radio Button类型不匹配错误解决方法

这个错误是Dart空安全机制导致的:Radio组件的选中值和回调参数是可空的int?类型,但你声明的_value是不可空的int,类型不兼容所以触发报错。以下是几种解决方式:

  • 修改变量类型为可空
    直接把_value的类型改成int?,和Radio的参数类型保持一致:

    int? _value = 1;
    
  • 使用非空断言(需确保值不会为null)
    如果你的业务逻辑能保证Radio的选中值永远不会是null,可以用!断言非空,强制转换为不可空int:

    int _value = 1;
    
    // 在Radio的onChanged回调里
    onChanged: (int? newValue) {
      setState(() {
        _value = newValue!;
      });
    }
    
  • 用空合并运算符设置默认值
    担心出现null的情况时,给一个默认值兜底,避免空值问题:

    int _value = 1;
    
    // 在Radio的onChanged回调里
    onChanged: (int? newValue) {
      setState(() {
        _value = newValue ?? 1; // newValue为null时,用1作为默认值
      });
    }
    

内容的提问来源于stack exchange,提问作者Omer Bayındır

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:04:53