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

24

我需要处理一个表单输入小部件上的返回按钮按下事件。以下是我实现的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 ????
    }
}

这部分代码是有效的,但会出现异常:

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

我该如何正确实现这个?


错误的原因是你没有在 if 外部或者 else 内部返回 bool 值。 - Blasanka
我尝试返回true,但IDE说它期望Future<bool>而不是bool类型。 - krishnakumarcn
你为什么使用了if条件语句? - Blasanka
我需要在按下返回按钮时显示警报。如果用户对数据进行了任何更改,则更改将变为true,此时我只需要显示警报。 - krishnakumarcn
@KrishnathkumarCN 您不必这样做,它会在 onWillPop 上进行处理。我已经添加了一个示例,请查看并如果它对您有用,请投票使其成为正确的答案。 - Blasanka
3个回答

51

我曾经遇到过完全相同的问题。

我通过返回Future.value(false)解决了这个问题;如果值为true,我会得到一片黑屏。

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

2
Future.value() 使我的一天得救了。感谢 @csigueros。 - Alok

8
导入 "dart:async" 包,并在您的方法签名中添加 async 关键字,例如:
Future<bool> _onWillPop() async{

完成后,您只需要像任何其他函数一样返回布尔值,表示方法已完成处理


你的错误信息“Failed assertion: boolean expression must not be null”可能意味着你在“if”条件中使用的布尔变量为空,因此请在使用它之前检查“changed”变量是否不为空,或者在你的“if”子句中添加“changed != null”条件。 - Ganapat

1

你的评论:我需要在按下返回按钮时显示警报。 如果用户对数据进行了任何更改,则更改将变为true,那时我只需要显示警报。

你不需要检查这个。

你可以参考下面的例子(来自官方材料示例,在这里你可以看到完整的例子),并获得一些想法:

import 'package:flutter/material.dart';
import 'dart:async';

bool _formWasEdited = false;

final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

Future<bool> _warnUserAboutInvalidData() async {
    final FormState form = _formKey.currentState;
    if (form == null || !_formWasEdited || form.validate())
      return true;

    return await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: const Text('This form has errors'),
          content: const Text('Really leave this form?'),
          actions: <Widget> [
            new FlatButton(
              child: const Text('YES'),
              onPressed: () { Navigator.of(context).pop(true); },
            ),
            new FlatButton(
              child: const Text('NO'),
              onPressed: () { Navigator.of(context).pop(false); },
            ),
          ],
        );
      },
    ) ?? false;
  }

在“表单(widget)”小部件中:
child: new Form(
    key: _formKey,
    autovalidate: _autovalidate,
    onWillPop: _warnUserAboutInvalidData,
    //........

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接