4

I'm using Getx to bind a stream to userDataModel. On initialization, the value is printed from the firestore database, but later the values are null.

When are try to print the value by using print(_userDataController.userDataModel.value.foodData); It prompts null.

PS: In a previous project, I used the identical code. There, it still works.

The code is as follows

UserModel:

  Map? foodData;
  UserDataModel({this.foodData});

  factory UserDataModel.fromMap({dynamic dbData}) {
    return UserDataModel(
      foodData: dbData['foodData'],
    );
  }
}

Controller

class UserDataController extends GetxController {

// ================================= >  Stream READ
  /// Stream User Model
  Rx<UserDataModel> userDataModel = UserDataModel().obs;

  /// Stream
  Stream<UserDataModel> dbStream() {
    return FirebaseFirestore.instance
        .collection('Users')
        .doc('user1')
        .snapshots()
        .map(
      (ds) {
        var _mapData = ds.data();
        print(_mapData); // ONINIT THIS DATA IS PRINTING BUT LATER IT PROMPTS THE ABOVE ERROR

        UserDataModel extractedModel = UserDataModel.fromMap(dbData: _mapData);
        return extractedModel;
      },
    );
  }

  /// FN to bind stream to user model
  void bindStream() {
    userDataModel.bindStream(dbStream());
  }

// ================================= >  OnInIt
  @override
  void onInit() {
    bindStream();
    super.onInit();
  }
}
2
  • I see no error in your code. The message "Instance of" doesn't mean it is an error. This message always shows whenever your printing an object. Commented Jul 21, 2022 at 1:07
  • But oninit() it does prints the actual value instead of instance. Why? @emmy-chwan Commented Jul 21, 2022 at 6:31

1 Answer 1

1

To know the content of the Instance of '_MapStream<DocumentSnapshot<Map<String, dynamic>>, UserDataModel>' try with foodData.toString()

You are getting this prompt because you are not converting the response into proper DataModel class.

You have to map the json to DataModel class. For that you can just paste the response which is printed in the console to https://jsontodart.com/ this will prepare the data model class for you. Then you can access the elements by iterating through them and getting corresponding instance variable

For reference refer:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.