Home > Back-end >  How to provide a `FutureOr<Null>` in a `catchError()` in a `FlutterLogin` with Firebase
How to provide a `FutureOr<Null>` in a `catchError()` in a `FlutterLogin` with Firebase

Time:12-20

I am trying to wire up Firebase auth method to the FlutterLogin callback as follows:

Future<String?> _authUser(BuildContext context, LoginData data) {
    debugPrint('Name: ${data.name}, Password: ${data.password}');

    return auth
        .signInWithEmailAndPassword(email: data.name, password: data.password)
        .then((credential) {

      return null;

    }).catchError((e) {
      if (e.code == 'weak-password') {
        debugPrint('The password provided is too weak.');
        return Future.error(e);
      } else if (e.code == 'email-already-in-use') {
        return 'The account already exists for that email.';
      } else {
        debugPrint(e.toString());  // <==== Where I get the exception
        return Future.error(e);
      }
    });
  }

I get the exception 'user-not-found' with is normal as the user does not exists yet. But how I can send the error back to FlutterLogin, as I am said to provide a FutureOr<null>?:

A value of type 'Future' can't be returned by the 'onError' handler because it must be assignable to 'FutureOr'

CodePudding user response:

The error occurred because returning invalid type in cathcError().

Your in your code Future.error() returns Future<dynamic> instaed of FutureOr<String?>

Future.catchError() constructor returns Future<T>. You can see this in the image.

The method in Future class

Future.error() is a factory constructor in Future class and it returns private future instance with generic (T) type. You can see this in the image again.

The factory constructor in Future class

So give generic type String? and String? property to Future<T>.error(). Fixed code:

Future<String?> _authUser(BuildContext context, LoginData data) {
debugPrint('Name: ${data.name}, Password: ${data.password}');

return auth
    .signInWithEmailAndPassword(email: data.name, password: data.password)
    .then((credential) {

  return null;

}).catchError((e) {
  if (e.code == 'weak-password') {
    debugPrint('The password provided is too weak.');
    return Future.error(e);
  } else if (e.code == 'email-already-in-use') {
    return 'The account already exists for that email.';
  } else {
    debugPrint(e.toString());
    return Future<String?>.error(e.code); // String? generic type gived.
  } 
});

}

  • Related