Pass variable to void function in flutter

Viewed 18324

I want to pass parameter from my dialouge box(Void function) to another void function but getting error

can't be assigned to the parameter type () void flutter

and setState also not working.

Please check my code here:

First function

  void _quantity(BuildContext context, productId,quantity){

    setState(() {
      productId = productId;
      quantity = quantity;
      _quantityController.text = '$quantity';
    });
    var alert = new AlertDialog(
     actions: <Widget>[
        FlatButton(
          child: Text("Save"),
          onPressed: _addtoCart(context, productId)
        )
      ],
    );

    showDialog(context: context,builder: (context) => alert);

  }

Second Function:

void _addtoCart(BuildContext context, productId) {
    print("Quantity: $quantity");
    print("productId: $productId");
    print("data: $data");
  }

Please check screenshot here

enter image description here

1 Answers

Change

onPressed: _addtoCart(context, productId)

to

onPressed: () => _addtoCart(context, productId)

to pass a function, instead of the result of a function call (the return value of _addtoCart() which returns void and produces the error.

If _addtoCart would not take any parameters, you could use the shorter form

onPressed: _addtoCart

but if you add () the function is invoked and the return value passed instead and with () => you can make it a function reference again or in this case a closure.

Related