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

Time:04-14

So for some background, I implemented a function that reads from Firebase's real-time database and returns a child node. I have built a button that is meant to check if that function returns the object or null if the function returns an object I want the snack bar to display a message.

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;
              }
            },

I had some success with the function by turning it into an async function

  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;
});

} When I turn it to an async function the snack bar displays the message but unfortunately even when the conditional is equal to a null, it for some reason continues to display the message and prints the "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

Any help would be appreciated and thanks for your time.

CodePudding user response:

add 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;
 }
}

CodePudding user response:

Try this approach, using the await in a variable will wait for the value then the if will evaluate what the result.

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;
                  }
                },
            )
  • Related