Home > OS >  The argument type 'int?' can't be assigned to the parameter type 'int'. flu
The argument type 'int?' can't be assigned to the parameter type 'int'. flu

Time:06-09

// I am getting an error at widget.product.id, // The argument type 'int?' can't be assigned to the parameter type '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);

    });
  }

CodePudding user response:

Your productCollection.get only accept a non-nullable int while your widget.product.id can be null.

A way of fixing this is either not call the function if it's null:

    updateRoutine() async {
    final productCollection = widget.isar.products;
    await widget.isar.writeTxn((isar) async {
      int? id = widget.product.id;
      if (id != null) {
         final product = await productCollection.get(id);

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

         await productCollection.put(product);
      }

    });
  }

Or add a default value to the parameter if your id is null (0 for this example)

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

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

      await productCollection.put(product);

    });
  }

CodePudding user response:

You can forcefully unwrap the product id and then assign it to an int variable

there are other way also

  1. give default value : int a = product.id ?? 1
  2. force unwrap : int a = prododuct.id!
  3. make optional variable : int? a = product.id
  • Related