Issue
I am trying to interact with the Firestore from a separate isolate. So far I am stacked on Firebase app initialization inside the isolate.
main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
print("Firebase app initialized in the main isolate");
ActivityReportHandler.instance.trackActivity();
}
activity_report_handler.dart
void trackActivityInBackground(message) async {
await Firebase.initializeApp();
print("Firebase app initialized in an isolate");
}
top-level function
While trying to initialize the FirebaseApp instance inside the isolate I get an exception
Unhandled Exception: Exception: Null check operator used on a null value
If I add WidgetsFlutterBinding.ensureInitialized()
on the first line of trackActivityInBackground
, I get an exception:
UI actions are only available on root isolate.
Under the hood, when await Firebase.initializeApp()
is called, after a series of calls finally the app tries to get binaryMessenger
, but when I dived deeper, I’ve noticed that both _binaryMessenger
and ServiceBinding.instance
are null here
BinaryMessenger get binaryMessenger => _binaryMessenger ?? ServicesBinding.instance!.defaultBinaryMessenger;
So the source of the crash is clear, what is not clear, is how to make it work? 😀
Thanks for the help in advance!
Solution
In refernce to this question the following github thread answers this question.
Answered By – Rajeev Tirumalasetty
Answer Checked By – Marilyn (FlutterFixes Volunteer)