Call Dart Code from Android Service – Guide
In this article
Yes, you can call Dart code from an Android Service by embedding a FlutterEngine in the app and using a MethodChannel to invoke Dart functions directly from the service.
What You'll Need
- Android Studio (latest stable version)
- Flutter SDK installed and added to your PATH
- A Flutter module or an existing Flutter project that contains the Dart code you want to run
- Basic knowledge of Kotlin (or Java) for Android development and Dart for Flutter
- Permission to run a foreground or background service (Android 9+ may require a foreground notification)
Step-by-Step
- Add the Flutter engine dependency. In your Android app's
build.gradle(app module) addimplementation "io.flutter:flutter_embedding_release:1.0.0". Sync the project so the Flutter engine libraries are available. - Create a custom Application class. Extend
Application(e.g.,MyApp : Application()) and initialize aFlutterEngineinonCreate():flutterEngine = FlutterEngine(this) flutterEngine.dartExecutor.executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault()) FlutterEngineCache .getInstance() .put("my_engine", flutterEngine)This starts the Dart isolate once for the whole process. - Declare the Application class in
AndroidManifest.xml. Addandroid:name=".MyApp"to the<application>tag. - Define the MethodChannel in the Application. After the engine is created, set up a channel that both the Android side and the Dart side will use:
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.service/channel") .setMethodCallHandler { call, result -> // This handler runs on the Dart side; keep it empty here. }The channel name must be identical on both sides. - Write the Dart function you want to call. In your Flutter module, add a top‑level function and register it with the same channel:
import 'package:flutter/services.dart'; const MethodChannel _channel = MethodChannel('com.example.service/channel'); Future<String> getDeviceInfo() async { // Example work: return Android version string. final String info = await _channel.invokeMethod('getDeviceInfo'); return info; } void registerHandlers() { _channel.setMethodCallHandler((call) async { switch (call.method) { case 'fetchData': // Perform any Dart‑side logic here. return 'Data from Dart'; default: throw PlatformException( code: 'Unimplemented', details: 'Method ${call.method} not implemented'); } }); } void main() { WidgetsFlutterBinding.ensureInitialized(); registerHandlers(); runApp(MyApp()); }TheregisterHandlers()call ensures the channel is ready before the service tries to invoke it. - Create the Android Service. In Kotlin, extend
Service(orJobIntentServicefor newer APIs). OverrideonStartCommand()and obtain the cached engine:override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val engine = FlutterEngineCache.getInstance().get("my_engine") if (engine == null) { Log.e(TAG, "FlutterEngine not found") stopSelf() return START_NOT_STICKY } methodChannel = MethodChannel(engine.dartExecutor.binaryMessenger, "com.example.service/channel") // Example call to Dart methodChannel.invokeMethod("fetchData", null, object : MethodChannel.Result { override fun success(result: Any?) { Log.i(TAG, "Dart returned: $result") } override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { Log.e(TAG, "Error from Dart: $errorMessage") } override fun notImplemented() { Log.w(TAG, "Method not implemented on Dart side") } }) return START_STICKY }Make sure the service runs on the main thread when interacting with the channel; the Flutter engine expects calls on its UI thread. - Start the service from an Activity or BroadcastReceiver. Use
ContextCompat.startForegroundService()for Android 9+ and provide a persistent notification if required. - Handle the result. The callback in step 6 receives the Dart return value. You can forward it to a local database, a UI component, or a remote server as needed.
- Clean up when the app terminates. In your
Applicationclass, overrideonTerminate()(only for debugging) or listen for process death and callflutterEngine.destroy()to free resources.
Common Mistakes
- Starting a new
FlutterEngineinside the service instead of reusing the cached one, which creates multiple Dart isolates and wastes memory. - Using a different channel name on the Android and Dart sides, causing
MethodNotImplementederrors. - Calling
invokeMethodfrom a background thread without posting to the main looper; the engine’s binary messenger is not thread‑safe. - Forgetting to add the foreground service permission (
android.permission.FOREGROUND_SERVICE) and the required notification, leading to the service being killed on Android 9+. - Not initializing the Dart side before the service tries to call it, which results in “no implementation found” errors.
Tips
- Cache the engine once in
Applicationand retrieve it withFlutterEngineCache. This pattern avoids repeated cold starts. - Keep the MethodChannel name short and descriptive; avoid using spaces or special characters.
- If you need to pass complex data, use JSON‑serializable maps rather than custom objects, because the channel only supports primitive types and simple collections.
- Use Kotlin coroutines to wrap
invokeMethodinsuspendCancellableCoroutinefor cleaner asynchronous code. - Test the Dart handler with
flutter runfirst, then attach the Android service later. This isolates Dart‑side bugs from service lifecycle issues.
Troubleshooting
Service does not receive a response. Verify that the engine is alive by checking the log for FlutterEngineCache retrieval. If engine == null, the Application may not have been started or the cache key is misspelled.
MethodNotImplemented error. Double‑check the exact method name string in both Kotlin ("fetchData") and Dart (case 'fetchData':). Remember that method names are case‑sensitive.
App crashes with IllegalStateException: Platform view is not attached. This occurs when you call invokeMethod before the Dart side has called registerHandlers(). Ensure WidgetsFlutterBinding.ensureInitialized() runs before any channel setup in main().
Background restrictions stop the service. On Android 10+ you may need to request REQUEST_IGNORE_BATTERY_OPTIMIZATIONS or use a foreground notification with startForeground(). Check the system logs for ActivityManager: Killing messages.
Memory leak warnings. If you create a new engine each time the service starts, the old engine may linger. Always destroy the engine in onDestroy() if you cannot reuse the cached instance.
If none of the above resolves the issue, try the following sequence: restart the device, update Android Studio and Flutter SDK to the latest stable releases, clean the project (./gradlew clean), and rebuild.
Frequently Asked Questions
Can I use this approach with a pure native Android app (no Flutter module)?
Yes. Add a Flutter module as a dependency, then follow the steps above. The module provides the Dart runtime without requiring a full Flutter UI.
Do I need a foreground notification for every service that calls Dart?
Only for services that run continuously in the background on Android 9 (API 28) or higher. Short‑lived services started by a user action can remain background‑only.
Is it safe to call Dart from a background JobIntentService?
It is safe as long as you invoke the method on the main thread of the cached engine. Use Handler(Looper.getMainLooper()).post { … } to marshal the call.
What data types can I pass through the MethodChannel?
The channel supports int, double, String, bool, byte[], List and Map of those types. For complex objects, encode them as JSON strings or maps.
Can I call multiple Dart functions from the same service?
Yes. Reuse the same MethodChannel and invoke different method names. Each call is independent and returns its own result.
What happens if the Dart isolate crashes?
The FlutterEngine will report an error on the Android log and the channel will stop responding. Restart the engine by creating a new FlutterEngine or by relaunching the application.