Emmanuel Njorodongo
Emmanuel Njorodongo

Reputation: 1302

No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() when using Flutter WorkManager

I am having a work manager where i register a one off task like below


Workmanager().registerOneOffTask(
     "SyncCartIdsToFirestore-${DateTime.now()}",
     "firestore",
     inputData: {
     "productId": widget.productId,
     "quantity": 1
 });

Below is where i am trying to store a document to collection cart when the WorkManager is executing in main.dart file

@pragma(
    'vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) async {
    switch (taskName) {
      case 'firestore':
        final productId = inputData!['productId'] ?? '';
        final quantity = inputData!['quantity'] ?? '';

        Logger().e("ProductId:: $productId");
        Logger().e("Quantity:: $quantity");

        Logger().e("InputData:: ${jsonEncode(inputData)}");

        Logger().e("UploadCartIdsToFirestoreCalled:: True");

        // print("WeArePrintingUsingPrinting:: bla bla bla bla");

        if (productId != null && quantity != null) {
          Logger().e("AddToFirestoreIfStatementReached:: True");

          final firestoreInstance = FirebaseFirestore.instance;

          try {
            await firestoreInstance.collection('cart').doc(productId).set({
              'quantity': quantity,
            });

            Logger().i("ProductAddedToCartWithId:: $productId");
            return Future.value(true); // Indicate success
          } catch (e) {
            Logger().e("FailedToAddProductToCart:: $e");
            return Future.value(false); // Indicate failure
          }
        }

        break;
      default:
    }
    return Future.value(true);
  });
}

Work manager Runs well until it reaches the try catch for storing the document then brings below error

E/BackgroundWorker( 2288): errorCode: error, errorMessage: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

I have tried moving WorkManager callbackDispatcher below FirebaseInitialization in the Future main function like below but the error is still the same


Future main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();

  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  await Hive.initFlutter();
  // Install build runner and run the build runner command in the model class
  Hive.registerAdapter(CartProductAdapter());
  await Hive.openBox<CartProduct>('cart');

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // wait for firebase initialization above because callbackDispatcher will call firestore
  Workmanager().initialize(
    callbackDispatcher,
    isInDebugMode: true,
  );

  runApp(const MyApp(useDevicePreview: false));
}

When i try to move the try catch part to a button that is inside a StatefulWidget it just works fine and save the document in cart collection the error only occurs when i am running the code for saving the document inside the WorkManager

Upvotes: 1

Views: 355

Answers (1)

prasad kirpekar
prasad kirpekar

Reputation: 31

I was having similar issue. It is related to firebase version For me it was resolved by running this command

dart pub upgrade

Upvotes: 0

Related Questions