简体   繁体   中英

Flutter - This function has a return type of 'FutureOr<XXX>', but doesn't end with a return statement

I want return a future with a value from a try catch block:

  Future<UserCredential> createUser(String email, String password) async {
    try {
      return FirebaseAuth.instance
          .createUserWithEmailAndPassword(email: email, password: password);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        Get.snackbar(
            'Error Creating Account', 'The password provided is too weak.',
            snackPosition: SnackPosition.BOTTOM);
      } else if (e.code == 'email-already-in-use') {
        Get.snackbar('Error Creating Account',
            'The account already exists for that email.',
            snackPosition: SnackPosition.BOTTOM);
      }
    } catch (e) {
      print(e);
      Get.snackbar('Error Creating Account', e.message as String,
          snackPosition: SnackPosition.BOTTOM);
    }
  }

But it gives this error:

This function has a return type of 'FutureOr<UserCredential>', but doesn't end with a return statement. Try adding a return statement, or changing the return type to 'void'.

Can I make this return a future that has a value in it and also handles the error in the function or do I have to change the return type to Future<void> ?

Your return value has to be of the type declared with the Future's generic type. If there are any code paths that don't return a UserCredential, then you can't use this declaration. If you have no return value, then yes, it should be Future<void> . But it seems that you do have a return value in at least one code path.

Consider instead moving all of the UI code out of this method and simply let the function throw whatever it throws (or re-throw something else). Then, make the caller of this function catch the error and decide what to show in the UI for that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM