Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() #372

Closed
wasim919 opened this issue Mar 29, 2022 · 6 comments
Closed
Labels
bug Something isn't working

Comments

@wasim919
Copy link

wasim919 commented Mar 29, 2022

Code:

void callbackDispatcher() async {
  Workmanager().executeTask(
    (taskName, inputData) async {
      await Firebase.initializeApp();
      await injection.init();
      try {
        switch (taskName) {
          case CREATE_POST_TASK_NAMESPACE:
            LocalNotificationHelper.showNotification(
              title: "Executing task: $taskName",
            );
            if (inputData != null) {
              String title = inputData[CREATE_POST_WORKMANAGER_TITLE_NAMESPACE];
              String? bodyText = inputData[CREATE_POST_WORKMANAGER_BODY_TEXT_NAMESPACE];

              await injection.di<FeedDataSource>().createPost(
                    title,
                    bodyText != null && bodyText.isEmpty ? null : bodyText,
                    null,
                    null,
                  );
            }
            break;
        }
        return Future.value(
          true,
        );
      } catch (e) {
        print(
          e,
        );
        return Future.error(
          e,
        );
      }
    },
  );
}

Workmanager().initialize(
      callbackDispatcher,
);

Response: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

@wasim919 wasim919 added the bug Something isn't working label Mar 29, 2022
@ened
Copy link
Collaborator

ened commented Apr 1, 2022

Can you confirm this issue still exists, and if so, submit a full stack trace perhaps, and perhaps also the adb logcat output.

@alperenbaskaya58
Copy link

alperenbaskaya58 commented Jul 2, 2022

Can you confirm this issue still exists, and if so, submit a full stack trace perhaps, and perhaps also the adb logcat output.

I can confirm. I have same issue

@gOzaru
Copy link

gOzaru commented Aug 1, 2022

@wasim919
@alperenbaskaya58

May I say a word about this?
Why do you have to register Firebase.initilizeApp() again?
I think you just need to create a separate function to do what you want within Firebase, and keep the default settings defined by FlutterFire. In my case, I used another GetxService so no one can remove this in memory. Then I added a function inside this GetxService class and call it within from callbackDispatcher(), just like this:

@pragma('vm:entry-point')
Future<void> callbackDispatcher() async {
  final Cloud cloud = Get.find();   //<-- I call the GetxService from here
  Workmanager().executeTask((task, inputData) async {
    switch (task) {
      case periodicTask:
        await cloud.startBackingUp();
        log("$periodicTask was executed");
        break;
      case failedTask:
        log('failed task');
        return Future.error('failed');
    }
    return Future.value(true);
  });
}

Oh yeah, you need to set 15 minutes time for minimum time for periodicTask.

await Workmanager().registerPeriodicTask(
   "backupSilently",
   periodicTask,
   initialDelay: const Duration(minutes: 3),
   frequency: const Duration(minutes: 15),
   constraints: Constraints(networkType: NetworkType.connected),
   existingWorkPolicy: ExistingWorkPolicy.keep,
   backoffPolicy: BackoffPolicy.exponential,
   backoffPolicyDelay: const Duration(seconds: 10),                 
);

Update:
I think I got a lot of error than you guys.
Maybe my approach was wrong.
You can view it on the image below.

SS - Workmanager error 01

@gOzaru
Copy link

gOzaru commented Aug 1, 2022

Okay, I just found out where I went wrong.
It seems I have to add this Firebase init() and use Get.put for the Controller, like the code below only in the current task I am gonna use it. So, outside of that task, any Firebase function will not be executed.

await Firebase.initializeApp();
final Cloud cloud = Get.put(Cloud());

Then the whole code is:

WidgetsFlutterBinding.ensureInitialized();
log("Running Workmanager()");
Workmanager().executeTask((task, inputData) async {
    switch (task) {
      case periodicTask:
        log("Executing periodicTask");
        await Firebase.initializeApp();
        final Cloud cloud = Get.put(Cloud());
        await cloud.startBackingUp();
        log("$periodicTask was executed");
        break;
      case failedTask:
        log('failed task');
        return Future.error('failed');
    }
    return Future.value(true);
});

SS - Workmanager error 02

The value you see under the green line is the value I get from Realtime Database.

In your case @wasim919,
You should declare Firebase.init() inside the name of current task CREATE_POST_TASK_NAMESPACE, like example above.
Do not declare it outside of taskName!
It will give an error.

Final Note:
I think the documentation needs to be updated: so that only required initialization which will be placed inside the task. All other initializations which are placed outside the task will not be excuted.
Thank you for making this free dart package.
Your team won't go unrewarded!

@gOzaru
Copy link

gOzaru commented Aug 1, 2022

Still get same error after success execution:

W/System  (16031): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(16031): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
[log] Check Device => Current id is null
[log] Check Device => data[id] is 0d7f0ef8a8ec91f3
[log] be.tramckrijte.workmanagerExample.simplePeriodicTask was executed: 195
E/BasicMessageChannel#(16031): Parameter messenger must not be null.
D/AndroidRuntime(16031): Shutting down VM
I/WM-WorkerWrapper(16031): Worker result SUCCESS for Work [ id=a53fcdd9-0f9c-43c9-8501-35621fd41d03, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
E/AndroidRuntime(16031): FATAL EXCEPTION: main
E/AndroidRuntime(16031): Process: com.sim.had, PID: 16031
E/AndroidRuntime(16031): java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.BinaryMessenger.setMessageHandler(java.lang.String, io.flutter.plugin.common.BinaryMessenger$BinaryMessageHandler)' on a null object reference
E/AndroidRuntime(16031): at io.flutter.plugin.common.BasicMessageChannel.setMessageHandler(BasicMessageChannel.java:132)
E/AndroidRuntime(16031): at io.flutter.plugins.firebase.auth.GeneratedAndroidFirebaseAuth$MultiFactorUserHostApi$-CC.setup(GeneratedAndroidFirebaseAuth.java:358)
E/AndroidRuntime(16031): at io.flutter.plugins.firebase.auth.FlutterFirebaseAuthPlugin.onDetachedFromEngine(FlutterFirebaseAuthPlugin.java:131)
E/AndroidRuntime(16031): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.remove(FlutterEngineConnectionRegistry.java:270)
E/AndroidRuntime(16031): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.remove(FlutterEngineConnectionRegistry.java:280)
E/AndroidRuntime(16031): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.removeAll(FlutterEngineConnectionRegistry.java:288)
E/AndroidRuntime(16031): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.destroy(FlutterEngineConnectionRegistry.java:121)
E/AndroidRuntime(16031): at io.flutter.embedding.engine.FlutterEngine.destroy(FlutterEngine.java:425)
E/AndroidRuntime(16031): at be.tramckrijte.workmanager.BackgroundWorker.stopEngine$lambda-2(BackgroundWorker.kt:137)
E/AndroidRuntime(16031): at be.tramckrijte.workmanager.BackgroundWorker.$r8$lambda$u5fs2CPxJ29Hdjbap5WYUt2tGrg(Unknown Source:0)
E/AndroidRuntime(16031): at be.tramckrijte.workmanager.BackgroundWorker$$ExternalSyntheticLambda1.run(Unknown Source:2)
E/AndroidRuntime(16031): at android.os.Handler.handleCallback(Handler.java:873)
E/AndroidRuntime(16031): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(16031): at android.os.Looper.loop(Looper.java:201)
E/AndroidRuntime(16031): at android.app.ActivityThread.main(ActivityThread.java:6820)
E/AndroidRuntime(16031): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(16031): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
E/AndroidRuntime(16031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
W/com.sim.had(16031): Accessing hidden method Ldalvik/system/CloseGuard;->close()V (light greylist, linking)
Lost connection to device.

It seems the cause is because I used the most updated Firebase package from Flutter Fire as shown in this link

The fix is in here
You need to update Firebase version.

@gOzaru
Copy link

gOzaru commented Aug 1, 2022

Okay, no more error at all.
It seems it was Firebase Auth bug from previous versions 3.5.0.
So you need to update them all to the latest.

SS - Workmanager error 03

@ened ened closed this as completed Aug 6, 2022
@fluttercommunity fluttercommunity locked and limited conversation to collaborators Aug 6, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants