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

Flutter报错:int?类型无法赋值给int类型参数如何解决

Flutter Isar更新逻辑int?无法赋值给int类型报错修复

报错场景

编写基于Isar数据库的产品信息更新方法updateRoutine时,代码中widget.product.id位置抛出空安全类型错误:

The argument type 'int?' can't be assigned to the parameter type 'int'
即参数类型为可空int?,无法赋值给要求非空int类型的形参

对应原始问题代码:

updateRoutine() async {
  final productCollection = widget.isar.products;
  await widget.isar.writeTxn((isar) async {
    final product = await productCollection.get(widget.product.id);

    product!
      ..name = nameController.text
      ..price = double.parse(priceController.text)
      ..quantity = int.parse(quantityController.text);

    await productCollection.put(product);

  });
}

报错原因

Isar的实体类id字段为自增主键时,默认类型是可空int?:对象未持久化到数据库时id值为null,写入数据库后Isar会自动为其分配自增id。而集合的get()方法要求传入非空int类型作为主键查询参数,直接传入可空的widget.product.id会触发Dart空安全校验报错。
另外原始代码直接对查询结果做!空断言也有风险,如果对应id的产品不存在,会直接抛出运行时异常。

修复方案

根据业务场景选择对应处理方式即可:

  • 场景1:当前逻辑为编辑已存在的产品,产品对象必然已经持久化、id一定非空(比如编辑页传入的是从数据库查出来的已有产品)
    先提取id做空判断,再传入查询方法,同时补全查询结果的空兜底,避免运行时崩溃,修复后代码如下:
    updateRoutine() async {
      final productCollection = widget.isar.products;
      // 提前提取id,为空直接终止更新逻辑
      final targetId = widget.product.id;
      if (targetId == null) return;
    
      await widget.isar.writeTxn((isar) async {
        final product = await productCollection.get(targetId);
        // 查询不到对应产品直接返回,避免空断言异常
        if (product == null) return;
    
        product
          ..name = nameController.text
          ..price = double.parse(priceController.text)
          ..quantity = int.parse(quantityController.text);
    
        await productCollection.put(product);
      });
    }
    
  • 场景2:逻辑同时支持新增和编辑产品,id可能为null
    可以用空值合并运算符给id设置一个不可能存在的兜底值,比如widget.product.id ?? -1,如果id为null时传入-1,查询结果必然为null,此时新建产品对象写入即可,示例逻辑:
    updateRoutine() async {
      final productCollection = widget.isar.products;
      await widget.isar.writeTxn((isar) async {
        // id为空时传-1,查询不到对应数据
        final existingProduct = await productCollection.get(widget.product.id ?? -1);
        final product = existingProduct ?? Product();
    
        product
          ..name = nameController.text
          ..price = double.parse(priceController.text)
          ..quantity = int.parse(quantityController.text);
    
        await productCollection.put(product);
      });
    }
    

注意:不要在未做任何空判断的前提下直接对widget.product.id加!空断言强行通过编译,一旦id实际为null会直接触发运行时崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 23:57:19