How To Run Firebase Queries In An Isolate In Flutter

1.6k Views Asked by At

Am trying to upload files to Firebase storage in an isolate but it doesn't seem to be working. I keep getting the following exceptions:

E/flutter ( 1527): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
E/flutter ( 1527): #0      MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
E/flutter ( 1527): #1      Firebase.app (package:firebase_core/src/firebase.dart:52:41)
E/flutter ( 1527): #2      FirebaseFirestore.instance (package:cloud_firestore/src/firestore.dart:43:21)
E/flutter ( 1527): #3      new ForumsProvider (package:trumate/src/providers/forums.provider.dart:31:41)
E/flutter ( 1527): #4      CommonProvider.videoPost (package:trumate/src/providers/common.provider.dart:100:29)
E/flutter ( 1527): <asynchronous suspension>
E/flutter ( 1527): #5      CommonProvider.backgroundVideoUpload (package:trumate/src/providers/common.provider.dart:112:5)
E/flutter ( 1527): #6      FlutterIsolate._isolateInitialize.<anonymous closure>.<anonymous closure> (package:flutter_isolate/flutter_isolate.dart:128

Am using flutter_isolate: ^1.0.0+14 plugin for that. But it seems running Firebase queries inside the isolate is the issue.

My main has await Firebase.initializeApp(); so I don't know I am getting such error.

3

There are 3 best solutions below

0
On BEST ANSWER

The isolates in Flutter are completely, well, isolated. Think of it a little bit like processes (in the sense that two isolates share (almost) no memory), instead of the traditional threads in Java or C in the sense of memory sharing.

Therefore, if you init your Firebase in your main isolate (as what you did in main), Firebase will not be inited in your other isolates. Thus, try to init it again in your other isolates.

1
On

I had the same problem and wasn't able to run Firestore within an isolate. I ended up using a Timer to handle it:

_MyAppState() {
  _timer = new Timer.periodic(Duration(seconds: 2), (timer) async {
   //Call function that handles firestore
   var upload = await fireUpload();
   //Returns value to despose timer if job is completed
   if (upload == false){
     dispose();
   }
  });
}

//Kills the Timer function
@override
void dispose() {
  super.dispose();
  _timer.cancel();
}
0
On
flutter_isolate: ^2.0.2


onPressed: () {
  FlutterIsolate.spawn(_isolateEntrypoint, "foo");
}

// A "top level" function (i.e. not inside a class or make it static)
_isolateEntrypoint(String foo) {
    WidgetsFlutterBinding.ensureInitialized();
    ...
}

Make sure that authorization and initialization were made on the same main thread (top level or static). Now this FlutterEngine will be able to communicate with Firebase storage.