Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facing 'No Firebase App has been created' while uploading to Firebase Storage in a Flutter app

I want to collect user browsing data for offline backend analysis for a Flutter app. What is the optimal way to do that?

What I am planning to do is run a daily cron on the app that uploads it using the WorkManager package.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  Workmanager().initialize(uploadUserData, isInDebugMode: true);
  Workmanager()
      .registerOneOffTask('1', 'task1', initialDelay: Duration(seconds: 10));
  runApp(MyApp());
}

void uploadUserData() {
  Workmanager().executeTask((task, inputData) {
    firebase_storage.FirebaseStorage.instance
        .ref('/uploads/test_workmanager.txt')
        .putString('workmanager test');
    return Future.value(true);
  });
}

I am facing the following issue while running the above code

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

I/WM-WorkerWrapper( 6733): Worker result FAILURE for Work [ id=81642715-826f-4d40-b8ec-9d86eab75136, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]

I have checked in multiple ways that firebase is initialized before calling the workmanager task (using firebase.apps.length & .whenComplete)

Update: Many are doubting whether firebase connection is right: basically everything just works if I just call firebase_storage....putString in the main() instead of within Workmanager().executeTask. So, the trouble is only due to Workmanager.

like image 712
kamalbanga Avatar asked Sep 11 '21 12:09

kamalbanga


1 Answers

  1. First call await Firebase.initializeApp(); in Workmanager().executeTask() async { }.

  2. I recommend also "awaiting" all the following Firebase actions in the Workmanager task: await firebase_storage.FirebaseStorage.instance.[...]. This is because without await, the Workmanager might consider the task finished and kill the process before the Firebase action finishes.

Full Workmanager example task code with changes:

Workmanager().executeTask((task, inputData) async {
  await Firebase.initializeApp();
  await firebase_storage.FirebaseStorage.instance
      .ref('/uploads/test_workmanager.txt')
      .putString('workmanager test');
  return Future.value(true);
});
like image 94
OvalOlive Avatar answered Jun 13 '23 22:06

OvalOlive