How can I run dart code in the background in flutter?

1,933

Solution 1

You can write the native code for Firebase realtime database. You can check this.

You should create a custom plugin and put the native code in that plugin as writing the files directly in the Flutter android folder will make the project unmanageable in the future and you can face multiple unexpected issues.

Solution 2

In Flutter, you can execute Dart code in the background.

The mechanism for this feature involves setting up an isolate. Isolates are Dart’s model for multithreading, though an isolate differs from a conventional thread in that it doesn’t share memory with the main program. You’ll set up your isolate for background execution using callbacks and a callback dispatcher.

For more information and a geofencing example that uses background execution of Dart code, see the Medium article by Ben Konyi, Executing Dart in the Background with Flutter Plugins and Geofencing. At the end of this article, you’ll find links to example code, and relevant documentation for Dart, iOS, and Android.

Share:
1,933
Manas Bam
Author by

Manas Bam

Updated on December 20, 2022

Comments

  • Manas Bam
    Manas Bam over 1 year

    I want to run a method in my main.dart file from the android(Kotlin) part of my app. For this I am using methodChannels and it works perfectly fine when the app is in foreground. However, the moment the app is killed, the flutterView is destroyed and therefore I am unable to run any methods in my main.dart file.

    I read that using FlutterNativeView would allow me to do what I want but I am unable to find small code snippets to help me with it.

    It would be great if you could help me with this

    Thanks!!

    • Sanjay Sharma
      Sanjay Sharma almost 4 years
      What exactly do you need to do through dart code which you can't do by Kotlin code in background?
    • Manas Bam
      Manas Bam almost 4 years
      Hi @SanjaySharma. I need to send background location data to firebase. I could not find any implementation to this in Kotlin and hence the question. It would really great of you could help me run the dart code or tell me a way to send data to firebase when the app is killed from Kotlin?
    • Sanjay Sharma
      Sanjay Sharma almost 4 years
      Which firebase service are you using?
    • Manas Bam
      Manas Bam almost 4 years
      realtime database
    • Sanjay Sharma
      Sanjay Sharma almost 4 years
      You can easily find native code for Firebase realtime db interaction. Check this
    • Manas Bam
      Manas Bam almost 4 years
      Thank you so much @SanjaySharma. Writing native Kotlin code worked!!!! This solved my issue! Thanks again!
  • Manas Bam
    Manas Bam almost 4 years
    Hi @san thanks for your answer! I think isolates and ports should do the job but I solved my issue by writing native Kotlin code. Thanks again!