简体   繁体   中英

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

在此输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM