Problem to recover UID from firebase Authentication?

Asked

Viewed 317 times

-2

I am trying to create a collection in Firebase and for the document of this collection I would like to take the authentication UID of the user registration, the registration of the authentication is ok but does not create the collection follows the code below:

the Code communicating with Firebase

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:flutter/material.dart';

class UserModel extends Model{

  FirebaseAuth _auth = FirebaseAuth.instance;

  FirebaseUser firebaseUser;
  Map<String, dynamic> userData = Map();

  bool isLoading = false;

  void signUp({@required Map<String, dynamic> userData, @required String pass, @required VoidCallback onSuccess, @required VoidCallback onFail}){
    isLoading = true;
    notifyListeners();

    _auth.createUserWithEmailAndPassword(
        email: userData["email"],
        password: pass
    ).then((user) async{
      AuthResult firebaseUser = user;

      await _saveUserData(userData);

      onSuccess();
      isLoading = false;
      notifyListeners();
    }).catchError((e) async{
      onFail();
      isLoading = false;
      notifyListeners();
      print("erro");
    });
  }

  void signIn() async{
    isLoading = true;
    notifyListeners();

    await Future.delayed(Duration(seconds: 3));

    isLoading = false;
    notifyListeners();
  }

  void recoverPass(){

  }

  Future<Null> _saveUserData(Map<String, dynamic> userData) async{
    this.userData = userData;
    print("teste $userData");
    await Firestore.instance.collection("users").document(firebaseUser.uid).setData(userData);
  }
}

the View Code of the Registration Form

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:loja_virtual/models/user_model.dart';
import 'package:scoped_model/scoped_model.dart';

class SignUpScreen extends StatefulWidget {
  @override
  _SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _passController = TextEditingController();
  final _addressController = TextEditingController();

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Criar Conta"),
          centerTitle: true,
        ),
        body: ScopedModelDescendant<UserModel>(
          builder: (context, child, model) {
            if (model.isLoading) {
              return Center(child: CircularProgressIndicator());
            } else {
              return Form(
                key: _formKey,
                child: ListView(
                  padding: EdgeInsets.all(16.0),
                  children: <Widget>[
                    TextFormField(
                      controller: _nameController,
                      decoration: InputDecoration(hintText: "Nome Completo"),
                      validator: (text) {
                        if (text.isEmpty) {
                          return "Nome Inválido!";
                        }
                      },
                    ),
                    SizedBox(height: 16.0),
                    TextFormField(
                      controller: _emailController,
                      decoration: InputDecoration(hintText: "E-mail"),
                      keyboardType: TextInputType.emailAddress,
                      validator: (text) {
                        if (text.isEmpty || !text.contains("@")) {
                          return "E-mail inválido!";
                        }
                      },
                    ),
                    SizedBox(height: 16.0),
                    TextFormField(
                      controller: _passController,
                      decoration: InputDecoration(hintText: "Senha"),
                      obscureText: true,
                      validator: (text) {
                        if (text.isEmpty || text.length < 6) {
                          return "Senha Inválida!";
                        }
                      },
                    ),
                    SizedBox(height: 16.0),
                    TextFormField(
                      controller: _addressController,
                      decoration: InputDecoration(hintText: "Endereço"),
                      validator: (text) {
                        if (text.isEmpty) {
                          return "Senha Inválido!";
                        }
                      },
                    ),
                    SizedBox(height: 16.0),
                    SizedBox(
                      height: 44.0,
                      child: RaisedButton(
                          child: Text(
                            "Criar Conta",
                            style: TextStyle(
                              fontSize: 18.0,
                            ),
                          ),
                          textColor: Colors.white,
                          color: Theme.of(context).primaryColor,
                          onPressed: () {
                            if (_formKey.currentState.validate()) {

                              Map<String, dynamic> userData = {
                                "name": _nameController.text,
                                "email": _emailController.text,
                                "address": _addressController.text
                              };

                              model.signUp(
                                  userData: userData,
                                  pass: _passController.text,
                                  onSuccess: _onSuccess,
                                  onFail: _onFail
                              );
                            }
                          }),
                    ),
                  ],
                ),
              );
            }
          },
        ));
  }

  void _onSuccess() {}

  void _onFail() {}
}

I analyzed that the problem is in the code below:

Firestore.instance.collection("users").document(firebaseUser.uid).setData(userData);

specifically in the firebaseUser.uid variable where printing on the screen returns me the error below:

E/flutter ( 916): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Nosuchmethoderror: The getter 'uid' was called on null. E/flutter ( 916): Receiver: null E/flutter ( 916): Tried Calling: uid E/flutter ( 916): #0 Object.noSuchMethod (Dart:core-patch/object_patch.Dart:53:5)

someone can help me?

1 answer

0

You are not loading the variable FirebaseUser firebaseUser, therefore the problem...

Create the following method

  Future<Void> currentUserUID() async {
    firebaseUser = await _firebaseAuth.currentUser();
  }

And before I call _saveUserData do

  void signUp({@required Map<String, dynamic> userData, @required String pass, @required VoidCallback onSuccess, @required VoidCallback onFail}){
    isLoading = true;
    notifyListeners();

    _auth.createUserWithEmailAndPassword(
        email: userData["email"],
        password: pass
    ).then((user) async{
      AuthResult firebaseUser = user;

      await currentUserUID();
      await _saveUserData(userData);

      onSuccess();
      isLoading = false;
      notifyListeners();
    }).catchError((e) async{
      onFail();
      isLoading = false;
      notifyListeners();
      print("erro");
    });
  }

This way your variable will receive the data needed to be used later.

If you want to take a look, in one of my sample projects I created a connection class with firebase, this one.

  • Matheus was just that, I did what you said and it worked, thank you very much for your help.

  • For nothing little guy, after do not forget to mark my answer as accepted, it helps those who come in search of similar solutions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.