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();
  }
}
Shakun's
  • 354
  • 4
  • 15
  • 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. – emmy-chwan Jul 21 '22 at 01:07
  • But oninit() it does prints the actual value instead of instance. Why? @emmy-chwan – Shakun's Jul 21 '22 at 06:31

1 Answers1

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:

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88