darthwithap
darthwithap

Reputation: 51

Unable to return custom 'User' instance of a user object created from firestore data in flutter

I have a custom 'User' class and I am trying to retrieve user's data from firestore based on its uid. I am successfully able to map it into my custom 'User' object however I cant return in from that function. Here is the code snippet:

class Wrapper extends StatelessWidget {
  // set activeUser globally
  User getCurrentUserObject(String uid) {
    User _user;
    var doc = DatabaseService().userCollection.document(uid);
    doc.get().then((doc) {
      _user = User().getUserFromData(doc.data);
      print(" user: $_user");
    });
    return _user;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context);
    final currentUser = Provider.of<FirebaseUser>(context);
    if (currentUser == null) {
      print("No user logged in");
      return Auth();
    } else {
      print("USER: ${getCurrentUserObject(currentUser.uid).email}");
      print("Current user: ${currentUser.uid}");
      return CustomerHomeScreen();
    }
  }
}

Here is the error snippet:

════════ Exception caught by widgets library ═══════════════════════════════════
The getter 'email' was called on null.
Receiver: null
Tried calling: email
The relevant error-causing widget was
    Wrapper 
lib/main.dart:20
════════════════════════════════════════════════════════════════════════════════
I/flutter (30822):  user: Instance of 'User'
I/flutter (30822):  user: Instance of 'User'

So far I have figured that it is not able return the User instance. How can i achieve that? Thank you :)

UPDATE: Adding User class which contains getUserFromData() method.


class User {
  final String uid;
  final String name;
  final String email;
  final String phone;
  final int gender;
  final int type;
  User({this.uid, this.name, this.email, this.phone, this.gender, this.type});

  User getUserFromData(Map<String, dynamic> data) {
    return User(
        uid: data['uid'] ?? '',
        name: data['name'] ?? '',
        email: data['email'] ?? '',
        phone: data['phone'] ?? '',
        gender: data['gender'] ?? -1,
        type: data['type'] ?? -1);
  }

  Map<String, dynamic> toJson() {
    return {
      'uid': uid,
      'name': name,
      'email': email,
      'phone': phone,
      'gender': gender,
      'type': type
    };
  }
}

Upvotes: 1

Views: 397

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7716

You're getting the error because your getCurrentUserObject method returns the _user variable before doc.get() completes. You can fix this by changing your code from using .then to using await, so you wait for the result of doc.get() before executing to the next line.

So, this:

User getCurrentUserObject(String uid) {
  //Rest of the code

  doc.get().then((doc) {
    _user = User().getUserFromData(doc.data);
    print(" user: $_user");
  });
  return _user;
}

becomes:

Future<User> getCurrentUserObject(String uid) async {
  //Rest of the code

  var doc =  await doc.get();
  _user = User().getUserFromData(doc.data);
  print(" user: $_user");
  return _user;
}

Upvotes: 2

Related Questions