简体   繁体   English

将变量传递给flutter中的void函数

[英]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 我想将参数从我的Dialouge框(Void函数)传递给另一个void函数,但是会出错

can't be assigned to the parameter type () void flutter 无法分配给参数类型()void flutter

and setState also not working. 和setState也无法正常工作。

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. 传递函数,而不是函数调用的结果( _addtoCart()的返回值返回void并产生错误。

If _addtoCart would not take any parameters, you could use the shorter form 如果_addtoCart不接受任何参数,则可以使用较短的形式

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. 但是如果你添加()函数被调用并且传递了返回值而使用() =>你可以再次使它成为函数引用,或者在这种情况下是一个闭包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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