我怎样才能离开一个函数?飞镖/扑扑

时间:2021-03-28 22:25:56

标签: flutter dart

嘿,我有一个带有 onPressed 的 ElevatedButton。在 onPressed 内部是一些 if 语句,可确保一切正确,然后我想将这些信息推送到 firebase。如果条件不满足,我如何离开 onPressed 函数?我尝试返回并返回 null,返回 0 但我的应用程序只是冻结。

ElevatedButton(
    onPressed: () async {
      if (date != null) {
        print(date);
      } else {
        dialog.showAlertDialog(context, 'Oops', 'You didn\'t choose a date!');
        return;
      }

      if (time != null) {
        print(time);
      } else {
        dialog.showAlertDialog(context, 'Oops', 'You didn\'t choose a time!');
        return 0;
      }

      if(combinedDateAndTime.isBefore(DateTime.now())) {
        dialog.showAlertDialog(context, 'Oops', 'Your date and time is in the past');
        return null;
      }
      
      _firestore.collection('foo').add({
        'dateTime': combinedDateAndTime,
      });
    },
    style: raisedButtonStyle,
    ),
  ),

我就是不知道如何离开这个函数。我将不胜感激。

1 个答案:

答案 0 :(得分:2)

一种方法是定义一个布尔变量并检查它是否为真,然后调用 firestore.collection,如下所示:

bool var = true;

if (date != null) {
    print(date);
  } else {
    dialog.showAlertDialog(context, 'Oops', 'You didn\'t choose a date!');
    var = false;
  }

  if (time != null) {
    print(time);
  } else {
    dialog.showAlertDialog(context, 'Oops', 'You didn\'t choose a time!');
    var = false;
  }

  if(combinedDateAndTime.isBefore(DateTime.now())) {
    dialog.showAlertDialog(context, 'Oops', 'Your date and time is in the past');
    var = false;
  }

  if (var == true){

  _firestore.collection('foo').add({
    'dateTime': combinedDateAndTime,
  });
  }
相关问题