繁体   English   中英

返回无效类型但不知道为什么? 颤振/飞镖

[英]Return of invalid type but don't know why? Flutter/Dart

嘿,我对 flutter 完全陌生,最近我一直在开发一款通过 BLE 从 ESP32 接收数据的移动应用程序,但我遇到的问题是,如果我想要求用户像这样断开与设备的连接:

Future<bool> _onWillPop() {
    return showDialog(
        context: context,
        builder: (context) =>
            new AlertDialog(
              title: Text('Are you sure?'),
              content: Text('Do you want to disconnect device 
              and go back?'),

             actions: <Widget>[
                new ElevatedButton(
                    onPressed: () => 
                      Navigator.of(context).pop(false),
                    child: new Text('No')),
                new ElevatedButton(
                    onPressed: () {
                      disconnectFromDevice();
                      Navigator.of(context).pop(true);
                    },
                    child: new Text('Yes')),
              ],
            ) ??
            false);
  }

它给了我错误警告:

A value of type 'Future<dynamic>' can't be returned from the method '_onWillPop' because it has a return type of 'Future<bool>'.

The return type 'Object' isn't a 'Widget', as required by the closure's context.

但是以我目前的知识,我不知道如何解决我的问题。 如果有人可以帮助我,我将非常感激:) 并对任何语法错误感到抱歉

未来<T?> showDialog

Future<T?> showDialog<T>(

    {required BuildContext context,
    required WidgetBuilder builder,
    bool barrierDismissible = true, 

无需return

该错误表明showDialogreturn类型不是 bool。 相反,您可以只用 await 替换,然后返回布尔值。

以下是您可以发布的代码。

Future<bool> _onWillPop(BuildContext context) async {
    bool shouldPop = false;
    await showDialog(
        context: context,
        builder: (context) =>
            AlertDialog(
              title: const Text('Are you sure?'),
              content: const Text('Do you want to disconnect device and go back?'),
             actions: <Widget>[
                ElevatedButton(
                    onPressed: () {
                      // shouldPop is already false
                    },
                    child: const Text('No')),
                ElevatedButton(
                    onPressed: () async {
                      await disconnectFromDevice();
                      Navigator.of(context).pop();
                      shouldPop = true;
                    },
                    child: const Text('Yes')),
              ],
            ));
    return shouldPop;
  }

我对代码进行了一些更改,以便在您不想弹出时返回 false,如果您想弹出则返回 true。 您可以根据您的要求更改代码。

暂无
暂无

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

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