Newaj
Newaj

Reputation: 4450

How to detect an async operation is successful or not in Flutter

In my app, after authentication, user can move to the next screen.

              signUpWithEmail().then((user) {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                  return HomePage();
                }));
              }).catchError((error) {
                print("THE ERROR : $error");
              });

Now signUpWithEmail may fail for various reasons like : invalid e-mail, internet connectivity failure and so on. How can I detect those errors and prevent navigation? Here is signUpWithEmail() method:

  Future<FirebaseUser> signUpWithEmail() async {
    String email = emailControlller.text;
    String password = passwordControlller.text;

    FirebaseUser user = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
      email: emailControlller.text,
      password: passwordControlller.text,
    )
        .then((user) {
      // set balance to 0
      Firestore.instance
          .collection("users")
          .document(user.uid)
          .setData({"cash": 0});
    }).catchError((e) => print("error : $e"));

    return user;
  }

Upvotes: 0

Views: 318

Answers (2)

Augusto
Augusto

Reputation: 4243

You is returning to signUpWithEmail() of anyway, you don't throw the error, so it never will enter on

.catchError((error) {
      print("THE ERROR : $error");
 })

To fix it you must throw the error on your signUpWithEmail(). Try something like it.

 Future<FirebaseUser> signUpWithEmail() async {
    String email = emailControlller.text;
    String password = passwordControlller.text;

    FirebaseUser user = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
      email: emailControlller.text,
      password: passwordControlller.text,
    )
        .then((user) {
      // set balance to 0
      Firestore.instance
          .collection("users")
          .document(user.uid)
          .setData({"cash": 0});
    }).catchError((e) => { 
        print("error : $e")
        throw("Your error") // It return to catch
    });

    return user;
   }

Let me know if you can make it.

Upvotes: 1

Loki
Loki

Reputation: 709

Use FutureBuilder widget and wrap the logic in the builder method

Upvotes: 0

Related Questions