'How to synchronously work with getx controllers, Getx

I am having a scenario , where i have to get Order details from user details i.e UserModel has a attribute of orders , which consists of array of orders,

But user details i.e UserModel will be filled from firebase.

So how to get order details from UserModel , after the UserModel is actually filled from the firebase.

By far my code:

UtilityController.dart

class UtilityController extends GetxController {
  static UtilityController instance = Get.find();
  Rx<UserModel> userModel = UserModel().obs;

  @override
  void onReady() {
    super.onReady();
    userModel.bindStream(listenToUser()); <-- I am using this to actaully fill the user details
  }

  Stream<UserModel> listenToUser() {
    return FirebaseFirestore.instance
        .collection("users")
        .doc(FirebaseAuth.instance.currentUser?.uid)
        .snapshots()
        .map((snapshot) => UserModel.fromSnapshot(snapshot));
  }

OrderController.dart

class OrderController extends GetxController {
  static OrderController instance = Get.find();
  RxList<OrderModel> orders = RxList<OrderModel>([]);

  @override
  void onReady() {
    super.onReady();
    orders.bindStream(getAllOrders());
    ever(utilityController.userModel, function); --> I am using this , but i know this is not the correct way
  }

  function(UserModel userModel) {
    getAllOrders();
  }

  Stream<List<OrderModel>> getAllOrders() {
    return FirebaseFirestore.instance
        .collection("orders")
        .where(FieldPath.documentId, whereIn: utilityController.userModel.value.orders)
        .snapshots()
        .map((query) => query.docs.map((item) => OrderModel.fromMap(item.data(), item.id)).toList());
  }
}

The utilityController.userModel.value.orders is null !!! it's not yet loaded, so all the orders are fetched :( And even if the orders are changed... But new orders are not fetched from the orders collection

How to get over this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source