【问题标题】:Can I pass an onpressed into a CupertinoDialog from a separate dart file in flutter我可以将一个 onpressed 从一个单独的 dart 文件中传递到一个 CupertinoDialog 中吗
【发布时间】:2020-10-25 19:29:51
【问题描述】:

我正在使用 CupertinoDialog 创建一个颤振应用程序。我在一个单独的 dart 文件中创建了对话框,所以我可以在多个地方调用它。这是我的对话框:

 void scanQR(BuildContext context) {
  showCupertinoDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: Text("Scan Qr Code"),
          content: Text("Scan the QR Code"),
          actions: [
            CupertinoDialogAction(
                isDefaultAction: true,
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  "Cancel",
                  style: TextStyle(color: CupertinoColors.systemRed),
                )),
            CupertinoDialogAction(
                isDefaultAction: true,
                onPressed: () {
                  
                },
                child: Text(
                  "Scan",
                  style: TextStyle(color: CupertinoColors.systemBlue),
                ))
          ],
        );
      });
}

这就是我在第二个屏幕上的称呼:

   onPressed: () {
      scanQR(context);
    }),

在我的第二个屏幕上,如果单击对话框上的“扫描”操作,我希望调用此函数。

  Future scanQrCode() async {
    try {
      String scanResult = await FlutterBarcodeScanner.scanBarcode(
          '#ffff00', 'cancel', true, ScanMode.QR);
      setState(() {
        scannedCode = scanResult;
      });
      print(scannedCode);
      if (scannedCode == widget.selectedUserId) {
 
      }
    } on PlatformException catch (e) {
      print(e);
    }
  }

当我将函数作为参数传递时,scanQrCode 会在按下按钮之前自动运行。

我该怎么办?

谢谢。

【问题讨论】:

  • 您能否分享创建您的对话框按钮的单独类的名称

标签: flutter dart


【解决方案1】:

您可以在小部件或函数的参数中传递函数。

 class MyButton extends StatelessWidget {
  final Function onPressed;
      
  const MyButton({
        Key key,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () => onPressed(),
    );
  }
}

然后

return MyButton(onPressed: () {
   print('clicked');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2020-10-24
    • 2014-04-20
    相关资源
    最近更新 更多