Home > OS >  Flutter Null cant be assigned to string
Flutter Null cant be assigned to string

Time:10-16

`this is my code I want to declare the id null however due to null safety i must declare it as id:'',But flutter doesnt consider it null . Below is my code

class _EditProductScreenState extends State<EditProductScreen> {
  final _priceFocusNode = FocusNode();
  final _descriptionNode = FocusNode();
  final _imgurlController = TextEditingController();
  final imgurlfocusnode = FocusNode();
  final _form = GlobalKey<FormState>();
  var editedproduct = Products_class(
    id: '',
    title: '',
    price: 0.0,
    description: '',
    imgurl: '',
  );

In the above instance i am not passing any id to the page so by default it should be null and add product should be called . However in here update product is called which gives me range error .How do i solve this issue ?

 void _saveform() {
    bool isValid = _form.currentState!.validate();
    if (!isValid) {
      return;
    }

    _form.currentState!.save();
    if (editedproduct.id == null) {
      Provider.of<products>(context, listen: false).addproduct(editedproduct);
    }
    if (editedproduct.id != null) {
      Provider.of<products>(context, listen: false)
          .updateProduct(editedproduct.id, editedproduct);
    }

    Navigator.of(context).pop();
  }

CodePudding user response:

You most likely declared your variable as String id; now, in the lower versions of dart be fore sound null safety that could happen but now you're using the current so make it a nullable type by adding ?

CodePudding user response:

Declare variable id of Product Class like

int? id; // id can now be null.

  • Related