skip to Main Content

I am trying to populate 2 values in my user profile. The values are name and email. I have implemented a function getCurrentUser which uses firebase authentication to get the current signed in user. I then use the uid for the user to query my users database were the name and email is stored.

Inside the function, if I print current user I get the users instance returning with values name, email and isStudent. When running my app is m getting the following error in the console "Warning: Operand of null-aware operation ‘!’ has type ‘Map<String, dynamic>’ which excludes null." I also get an error on the phone UI saying "LateInitializationError: Field ‘name’ has not been initialized"

Any advice on this is much appreciated!

I have attached the screenshot of the error and code snippet including variables,function and the variable call to display the values.

enter image description here

enter image description here

final _firestore = FirebaseFirestore.instance;
late User loggedInUser;

class MenuLecturerScreen extends StatefulWidget {
  static const String id = 'menu_lecturer';

  @override
  _MenuLecturerScreenState createState() => _MenuLecturerScreenState();
}

class _MenuLecturerScreenState extends State<MenuLecturerScreen> {
  final messageTextController = TextEditingController();
  final _auth = FirebaseAuth.instance;
  late String messageText;
  //String name = 'Eoin Irwin';
  //String email = '[email protected]';
  late String name;
  late String email;

  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = _auth.currentUser;

      await FirebaseFirestore.instance
          .collection("users")
          .doc(user?.uid)
          .get()
          .then((value) {
        final Map<String, dynamic>? currentUser = value.data();
        email = currentUser!['email'];
        name = currentUser!['name'];
        print(currentUser);
      });


      //print(FirebaseFirestore.instance.collection("users").doc(user?.uid).get());

      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  signOut() async {
    await _auth.signOut();
    Navigator.pushNamed(context, WelcomeScreen.id);
  }

  @override
  Widget build(BuildContext context) {
    var drawerHeader = UserAccountsDrawerHeader(
      accountName: Text(name),
      accountEmail: Text(email),

enter image description here

2

Answers


  1. By adding a ? You mentioned that the map can be null but then if you added ! You are mentioning that is not null and has a value.. try adding ? Instead

    
       final Map<String, dynamic>?currentUser = value.data();
            email = currentUser?['email']??"";
            name = currentUser?['name']??"";
            print(currentUser);
    

    Edit

    String name = "";
    String email = "";
    
    Login or Signup to reply.
  2. You are using a async method. And after getting data you are not using setState to update the UI.

      await FirebaseFirestore.instance
              .collection("users")
              .doc(user?.uid)
              .get()
              .then((value) {
            final Map<String, dynamic>? currentUser = value.data();
            email = currentUser!['email'];
            name = currentUser!['name'];
            print(currentUser);
            setState((){});
          });
    

    Also initially name, messageText and email are null. better use nullable data here

       String? messageText;
       String? name;
       String? email;
    

    Reading map can provide null, for safe case accept null data

    email = currentUser?['email'];
    name = currentUser?['name'];
    

    And while using it do

    Text(name??"")
    

    Future takes some time to fetch data until then variables are null .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search