skip to Main Content

I have this function to get userData into model:

Future<UserModel> getUser() async {
    final snap = await _fireStore
        .collection("users")
        .doc(_firebaseAuth.currentUser?.email ??
            _firebaseAuth.currentUser?.phoneNumber)
        .get();
    final data = snap.data();
    debugPrint("data: $data"); // this line gives output
    // debugPrint("data: ${jsonDecode(data.toString())}"); -> this line doesn't give any output either
    final user = UserModel.fromMap(data!);
    debugPrint("user : $user"); // this line doesn't gives output
    return user;
  }

I have already checked the parsing function UserModel.fromMap

factory UserModel.fromMap(Map<String, dynamic> map) => return UserModel(...);

It has no issues. I also tried using jsonDecode directly on data. That too doesn’t return any value. Does anyone have any suggestions on what could i be doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    The Function I made doesn't have any issues. The data I am parsing contains some complex data types such as Map, lists, Models and Sub-models. I used json_serializable: ^6.7.1 to resolve the issue, as some of the data wasn't getting parsed earlier.


  2. Add a null check condition like this, in most cases ‘!’ operator causes the issue, and try to avoid the ‘!’ operator

    So make your code like this and try:

    Future<UserModel> getUser() async {
        final snap = await _fireStore
            .collection("users")
            .doc(_firebaseAuth.currentUser?.email ??
                _firebaseAuth.currentUser?.phoneNumber)
            .get();
       final data = snap.data();
       if (data != null) {
          debugPrint("data: $data");
          final user = UserModel.fromMap(data);
          debugPrint("user: $user");
          return user;
       } else {
          debugPrint("data is null");
          return null;
        }
    
      }
    

    I hope this will solve you issue

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