Display error message outside build widget

Viewed 137

I am using a Model class to authenticate user before registering or logging.the problem is that i don't know a way to print error message to the user in snackbar,because no widget is defined in this class.

How can i display error message to user from Model Class?

Model class:

class FireAuth {


  static Future<User> registerUsingEmailPassword({
     String name,
     String email,
     String password,
  }) async {
    FirebaseAuth auth = FirebaseAuth.instance;

    User user;

    try {
      UserCredential userCredential = await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );

      user = userCredential.user;
      await user.updateDisplayName(name);
      await user.reload();
      user = auth.currentUser;

      //check if email is registered before

      //add user data to firestore
      CollectionReference users = FirebaseFirestore.instance.collection('users');
      users.doc(user.uid).set({
        'uid':user.uid,
        'img_url':'0',
        'name': name,  
        'phone': '',  
        'email': email, 
        'job_title':'',
        'university':'',
        'procedures':'',
        'expert_in':'',

      })
          .then((value) => print("User Added"))
          .catchError(
              (error) => print("Failed to add user: $error"));


    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');


      }
    } catch (e) {
      print(e);
    }

    return user;
  }
}

I need 'The account already exists for that email.' error message to display to user,not only printing it in log.

1 Answers

Excellent question, and I'll try to answer in the general so as to benefit your overall pattern in handling this very important case.

Depending on BuildContext is a common inconvenience in flutter. And it often comes up, but for good reason. You can think of it like this: You need the context because you need to specify where in the tree that UI is going to show. Knowing how to handle these cases makes the difference between beginner and more advanced flutter developers.

So one way is to pass the BuildContext around, but I wouldn't recommended it.

Lets say I have a function foo that returns some Future Rather than change the signature of the function to accept context, you can simply await the function and use the context in the callback already in your UI. For example,

instead of



Future foo(BuildContext context) {
  try {
    // await some async process
    // Use context to show success.
  } catch (e) {
    // Use context to show failure.
  }
}

You can do this

GestureDetector(
  onTap: () async {
    try {
     await foo();
     // Use context to show success.
    } catch (e) {
     // Use context to show failure.
    }         
  },
  child: // some child
),

The point is in the second example the context is already there in the widget. The signuture of foo is simpler. It requires some restructuring. Here I'm assuming that the series of events is traced back to a GestureDetector but it could be anything else.

Related