简体   繁体   中英

The getter 'user' was called on null on a Firebase Realtime Database + Flutter App

Today i updated the android emulator i use frecuently and for some reason im getting this error. I already update all possible dependences and packages.

I/FirebaseAuth(11346): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System  (11346): Ignoring header X-Firebase-Locale because its value was null.
E/flutter (11346): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'user' was called on null.
E/flutter (11346): Receiver: null
E/flutter (11346): Tried calling: user
E/flutter (11346): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (11346): #1      _RegistrarseState.signupNewUser (package:mundoplay/code/registrarse/registrarse.dart:511:9)
E/flutter (11346): <asynchronous suspension>

This is part of my current code for the user to register:

 final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  void signupNewUser(BuildContext context) async {

    showDialog(context: context,
        barrierDismissible: false,
        builder: (BuildContext context)
        {
          return barraProgreso(mensaje: "Creando su cuenta, espere...",);
        });

    final firebaseUser = (await _firebaseAuth
        .createUserWithEmailAndPassword(
        email: email.text, password: password.text)
        .catchError((errMsg) {
      Navigator.pop(context); 
      setState(() {
        _error = Errors.show(errMsg.code);
      });
    })).user;

    if (firebaseUser != null) 
        {

      Map userDataMap = {
        "nombre": nombre.text.trim(),
        "apellido": apellido.text.trim(),
        "email": email.text.trim(),
        "password": password.text.trim(),
        "celular": celular.text.trim(),
        "direccion": direccion.text.trim(),
        "localidad": localidad.text.trim(),

      };

      usersRef.child(firebaseUser.uid).set(userDataMap).then((value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('email', email.text);

        //Navigator.push(context, new MaterialPageRoute(builder: (context) => new SeleccionarConsola()));

      });

My register and login works with a form with TextEditingControllers that are set to the controller value.

I'm working with the firebase realtime database... any extra info, just ask me and i will try add it. THANKS!

According to the docs , catchError

Returns a new Future that will be completed with either the result of this future or the result of calling the onError callback.

So when you initialize your firebaseUser , you use a catchError that doesn't return nothing (ie implicitely returns null). You can see this in practice with a simple example:

Future<T> handleError<T>(Future<T> future) {
  return future.catchError((e) {
    print("An error occurred.");
    // Not returning anything here!
  });
}

void main() async {
  // When no error occurs, it will print 1
  print(await handleError(Future.value(1)));
  // When an error occurs, it will print null
  print(await handleError(Future.error(Error())));
}

Since you've already said that you're not connected to the internet since you're using an emulator, an error is being thrown inside the future (maybe a "no internet exception" kind of error), the future is returning null and thus the "The getter 'user' was called on null." message.

There are two ways you can avoid this:

  1. Using the ?. operator:
final firebaseUser = (await _firebaseAuth
        .createUserWithEmailAndPassword(
        email: email.text, password: password.text)
        .catchError((errMsg) {
      Navigator.pop(context); 
      setState(() {
        _error = Errors.show(errMsg.code);
      });
    }))?.user; // <- use it here!
  1. Doing it step-by-step:
final result = await _firebaseAuth.createUserWithEmailAndPassword(
  email: email.text,
  password: password.text,
).catchError((e) {
  Navigator.pop(context); 
  setState(() => _error = Errors.show(errMsg.code));
});

// Early exit
if (result == null) return;

// Only retrieve the firebase user here
final firebaseUser = result.user;

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