Flutter get data from Firebase with workmanager

149 views Asked by At

Is it possible to get data from Firebase using the WorkManager dependency? I tried to use Stream Builder but for some reason I can't get the data using the WorkManager. If there is a way, can you help please. I have initialized the WorkManager in the main.dart and also called it in a button widget and I used it to update data in the database and it works. I just want that the WorkManager should read the database so I can use it for further functions.

How can I do this?

@pragma("vm:entry-point")
void callbackDispatcher() async {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().executeTask((taskName, inputData) async {
    
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    final uid = FirebaseAuth.instance.currentUser!.uid;


    switch (taskName) {
      case "getData":
        try {
          final prefs = await SharedPreferences.getInstance();
          await prefs.setInt("value", 100);
          
            StreamBuilder(
              stream: FirebaseFirestore.instance
                  .collection("collectionName")
                  .doc(uid)
                  .snapshots(),
              builder: (context, snapshot) {
                final postStatus = snapshot.data?["PostStatus"];
                print("The post status time is ........ $postStatus");
                return const SizedBox();
              },
            );
          }
        } catch (err) {
          // Logger().e(err.toString());
          throw Exception(err);
        }
        break;
    }

    return Future.value(true);
  });
}

PS: I can update data in the database using the WorkManager so that's not a problem. The problem is getting data from the database because I want to run some functions for it

0

There are 0 answers