Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to void function in flutter

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

like image 1000
Rahul Mishra Avatar asked Aug 28 '18 13:08

Rahul Mishra


People also ask

How do you pass a void function in Flutter?

to pass a function, instead of the result of a function call (the return value of _addtoCart() which returns void and produces the error. 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.

How do you call void in Flutter?

To call a void function from another file in Flutter, what you have to do are: DO NOT name the function with the underscore symbol ( _ ) at the beginning. For instance, _myFunction() cannot be called in another file. Import the file that contains the function.


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.

like image 108
Günter Zöchbauer Avatar answered Oct 17 '22 12:10

Günter Zöchbauer