如何将函数输出用作 IF ELSE 或三元运算符的条件

How to use function output as a conditional of IF ELSE or Ternary operator

因此,对于某些背景,我实现了一个从 Firebase 的实时数据库和 returns 子节点读取的函数。我已经构建了一个按钮,用于检查该函数 returns 对象是否为 null,如果函数 returns 是一个对象,我希望小吃店显示一条消息。

ElevatedButton(
            onPressed: () {
              if (validateUsername() != null) {
                print("conditional: test");
                ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                    content: Text(
                        "Username has been taken please try a different one"),
                    duration: Duration(seconds: 5)));
              } else {
                return null;
              }
            },

我通过将函数转换为异步函数而取得了一些成功

  validateUsername() async {
final database = FirebaseDatabase.instance.ref().child("/takenUsernames");
await database
    .child(_usernameController.text.trim())
    .once()
    .then((DatabaseEvent event) {
  final snapShot = event.snapshot;
  final value = snapShot.value;
  print("function result: $value");
  return value;
});

} 当我把它变成一个异步函数时,小吃店显示消息但不幸的是,即使条件等于 null,它出于某种原因继续显示消息并打印“test”output. But if I were to try taking away the async the snack bar doesn't print and the "test" in the conditional doesn't print.non-async output

如有任何帮助,我们将不胜感激,感谢您抽出宝贵时间。

添加try/catch

 validateUsername() async {
try {
final database = FirebaseDatabase.instance.ref().child("/takenUsernames");
await database
    .child(_usernameController.text.trim())
    .once()
    .then((DatabaseEvent event) {
  final snapShot = event.snapshot;
  final value = snapShot.value;
  print("function result: $value");
  return value;
});
} catch(e) {
  print("err $e");
  return null;
 }
}

尝试这种方法,在变量中使用 await 将等待值,然后 if 将评估结果。

ElevatedButton(
                onPressed: () async {
                  String validation = await validateUsername(); // I used type String but you should use the type that will be return.
                  if (validation != null) {
                    print("conditional: test");
                    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text(
                            "Username has been taken please try a different one"),
                        duration: Duration(seconds: 5)));
                  } else {
                    return;
                  }
                },
            )

感谢@WilsonToribio 的帮助,我能够使用他提供的信息并对 validateUsername() 函数进行一些更改 如此处所示

  validateUsername() async {
try {
  final database = FirebaseDatabase.instance.ref().child("/usernames");
  final response = await database
      .child(_usernameController.text.trim())
      .once()
      .then((event) {
    final dataSnapshot = event.snapshot;
    if (dataSnapshot.value != null) {
      return dataSnapshot.value;
    }
  });
  return response;
} catch (e) {
  print("err $e");
  return null;
}

}