如何从Dart中的函数返回Future或任何其他类型

Kri*_* CN 4 dart flutter

我需要处理我的一个Form条目小部件上的后退按钮按下。这就是我实现WillPopScope的onWillPop方法的方式:

Future<bool> _onWillPop() {
    if (changed) {
       return showDialog(
        context: context,
        builder: (context) => new AlertDialog(
              title: new Text('Save'),
              content: new Text("Do you want to save the changes?"),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: new Text('No'),
                ),
                new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(false);
                    saveMeeting();
                  },
                  child: new Text('Yes'),
                ),
              ],
            ),
      ) ??
      false;
    } else {
      print("No changes");
      Navigator.of(context).pop(true);
      //return some future null from here ????
    }
}
Run Code Online (Sandbox Code Playgroud)

这部分代码正常工作,但出现异常:

[ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 7374): Failed assertion: boolean expression must not be null
Run Code Online (Sandbox Code Playgroud)

如何正确实施?

小智 8

我有完全一样的问题。

我通过返回Future.value(false);来解决它 如果值为true,则显示黑屏。

Future<bool> _onBackPressed() {
 if (!widget.editing) {
   Navigator.pop(context, true);
   return Future.value(false);
 } else {
   return showDialog(...
Run Code Online (Sandbox Code Playgroud)

  • `Future.value()` 救了我的命。谢谢@csigueros (2认同)

Gan*_*pat 7

导入“dart:async”包,并将 async 关键字添加到您的方法签名中,例如

Future<bool> _onWillPop() async{
Run Code Online (Sandbox Code Playgroud)

在此之后,只要您的方法完成其处理,就像任何其他函数一样,您只需要返回一个布尔值