Sub topic 9
Debugging an embedded Flutter module
When Flutter runs inside a native app, you still want the fast loop you get in a normal Flutter project: hot reload, breakpoints, and DevTools. The tool that provides it is flutter attach. This chapter explains how it works, how to use it on Android and iOS, and which problems come up most often.
This chapter assumes you have a Flutter module integrated into an Android or iOS host app, that you know how to build and run the host from Android Studio or Xcode, and that you are comfortable with the flutter command line. You should also know that the host owns a FlutterEngine and shows Flutter through a FlutterActivity or FlutterViewController.
Why `flutter run` is not enough
In a normal Flutter app, flutter run builds the app, installs it, starts it, and connects to it. In add-to-app, the native project is the one that builds and launches the app. The Flutter tool does not know about it.
If you run flutter run inside the module, it builds the module's own hidden host project (.android or .ios). That is a useful way to test the Dart code alone. It does not run your real app with your native code, your engine cache, or your channel handlers.
To debug the real app, you start it from Android Studio or Xcode and then connect the Flutter tool to the Dart code that is already running. That connection is called attaching.
How `flutter attach` works
A debug build of the Flutter engine runs the Dart VM in a mode that exposes the Dart VM Service. This is a local WebSocket endpoint. Hot reload, breakpoints, the widget inspector, and DevTools all talk to this endpoint.
flutter attach finds the VM Service of a running app and connects to it. It then behaves like flutter run from that point: you can press r for hot reload and R for hot restart, and you can open DevTools.
The tool finds the service in one of two ways:
- On Android, it asks the device for the app's service port and forwards it to your computer using
adb. - On iOS, it uses mDNS (a local network discovery protocol) to find the service advertised by the running app.
The basic workflow
Follow these steps for a normal debug session.
- Build and run the host app in debug mode from Android Studio or Xcode. A release or profile build does not expose a debuggable VM Service.
- Navigate in the app until a Flutter screen is showing, or until the engine has started.
- In a terminal, go to the module directory and attach.
cd my_flutter_module
flutter attachWhen the connection succeeds, the terminal prints the usual list of keys. Press r to hot reload your Dart changes, R to hot restart, and q to detach.
You can also attach from an IDE. In Android Studio or VS Code with the Flutter plugin, use the "Flutter Attach" command or a launch configuration with the attach request type. Breakpoints in your Dart files then work as in any Flutter app.
Attaching before the engine starts
If your app pre-warms the engine in Application.onCreate (Android) or at launch (iOS), the Dart code is running before any Flutter screen is visible. You can attach at that point.
If the engine starts later, for example when the user opens the first Flutter screen, run flutter attach first. It waits and connects as soon as the app starts a Dart VM:
flutter attach --device-id <device-id>Use flutter devices to list device IDs. This is helpful when several devices or simulators are connected.
Choosing the right app and device
flutter attach connects to one device at a time. If more than one is connected, pass -d. Both of these forms work:
flutter devices
flutter attach -d emulator-5554If the host app runs several Flutter engines (see the chapter on FlutterEngineGroup), each engine has its own VM Service. Attach can list the candidates, and you can pick one by its URI.
flutter attach --debug-url http://127.0.0.1:50000/abcdEFG=/The VM Service URL is printed in the native log (Logcat on Android or the Xcode console on iOS) when the engine starts in debug mode. Look for a line that begins with The Dart VM service is listening on.
Hot reload inside a host app
Hot reload sends changed Dart source to the running VM. Widgets rebuild with their existing state. A few rules apply in add-to-app.
- Only Dart changes reload. If you change Kotlin, Swift, or any native file, you must rebuild and relaunch the host app from the native IDE.
- A change to a Dart
main()or to the body of an entrypoint function does not take effect on hot reload, because the entrypoint has already run. Use hot restart. Note that hot restart restarts the Dart code in the engine, but it does not restart the native app. - If you change a platform channel handler on the Dart side, hot reload applies. If you change the matching handler on the native side, you need a native rebuild.
- State in a cached engine survives when the Flutter screen closes. After a hot restart, the state is reset. Remember this when a bug appears only after you reopen a screen.
Debugging platform channel calls
Bugs between the host and Dart are the most common add-to-app problem. The following table lists symptoms and their usual causes.
| Symptom | Likely cause | What to check |
|---|---|---|
| `MissingPluginException` on the Dart side | No handler registered for that channel name or method, or the handler was registered on a different engine | Channel name matches exactly on both sides. The handler is set on the engine that runs the screen. |
| Call never returns | The native handler never calls `result.success`, `result.error`, or `result.notImplemented` | Every branch in the handler must call one of them. |
| `PlatformException` | The native handler returned an error | Read the code and message. Check the native log for a stack trace. |
| Type error when reading a result | Native sent a type the Dart side did not expect | Print the value. Compare it with the codec types, such as `String`, `int`, `List`, `Map`. |
| Works in module, fails in host | Handler exists only in the host | Run the real host app and attach, instead of `flutter run` on the module. |
The MissingPluginException case also has a timing cause. If Dart calls a method in initState before the native code has registered the handler, the call fails. On Android, set the handler right after you create the engine, before you run the entrypoint. On iOS, register handlers before the first Flutter screen appears.
Here is a small Dart wrapper that makes channel failures easier to read in the debug console.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
const _channel = MethodChannel('com.example.host/session');
Future<String?> getUserName() async {
try {
return await _channel.invokeMethod<String>('getUserName');
} on MissingPluginException {
debugPrint('No native handler for getUserName on com.example.host/session');
return null;
} on PlatformException catch (e) {
debugPrint('Native error ${e.code}: ${e.message}');
return null;
}
}Reading logs from both sides
You have two log streams, and each one tells you something different.
- Dart
printanddebugPrintoutput appears in the terminal runningflutter attach. It also appears in Logcat on Android and in the Xcode console on iOS. - Native logs appear only in Logcat or Xcode. They do not appear in the
flutter attachterminal.
When a channel call fails, read both. The Dart side shows what was asked. The native side shows what the handler did.
On Android, filter Logcat by the tag flutter to see Dart output and engine messages. On iOS, filter the Xcode console by the word flutter.
Debugging native and Dart together
You can run a native debugger and flutter attach at the same time. This is the usual way to follow a call across the boundary.
- Start the host app from the native IDE with the debugger attached. Set a breakpoint in the native channel handler.
- Run
flutter attachor attach from your Dart IDE. Set a breakpoint in the Dart code that calls the channel. - Trigger the action. The Dart breakpoint pauses first. Resume. The native breakpoint pauses next.
Pausing at a native breakpoint freezes the platform thread. The Flutter UI may also seem frozen if it needs a reply from native code. This is expected.
On iOS, Xcode attaches to the process as the debugger. Flutter's debug engine on a physical device runs in JIT mode, so running the app from the home screen after a debug install may fail on newer iOS versions. Start debug sessions from Xcode or from the Flutter tool.
Using DevTools
After you attach, the terminal prints a link to DevTools. DevTools works as usual with an embedded module:
- The widget inspector shows only the widgets that Flutter draws. Native views do not appear in it.
- The performance view measures Flutter frames. It does not measure native work on the host side.
- The memory view shows the Dart heap. Memory used by native views and by the engine itself is not part of it, so use Android Studio's profiler or Xcode Instruments for those.
Common errors when attaching
| Problem | What to do |
|---|---|
| `flutter attach` waits forever | Check that the host app is a debug build, that the engine has started, and that the correct device is selected with `-d`. |
| Attach connects, then the app crashes on reload | A native-side change needs a rebuild. Stop, rebuild from the native IDE, and attach again. |
| iOS simulator is not found | Make sure the Mac and simulator are on the same network setup, and that local network access is not blocked by a firewall or VPN. |
| iOS physical device is not found | Allow local network access for the app when iOS asks. Without it, mDNS discovery fails. Use `--debug-url` as a fallback. |
| Breakpoints are never hit | The IDE is attached to a different engine or device, or the code is in a function that has already run. Use hot restart. |
| Stale behavior after code changes | The module was built as a prebuilt AAR or framework. Rebuild the module and sync the host project. Attach only updates source that the running VM loads. |
A debugging checklist
When something fails in the embedded module, work through these questions in order.
- Does the Flutter screen work when you run the module alone with
flutter run? If not, the problem is in Dart. - Does the host app launch the correct engine, entrypoint, and route? Check the log for the entrypoint name.
- Do the channel names and method names match exactly on both sides?
- Is the handler registered on the engine that the screen uses?
- Is the host built in debug mode and linked to the debug module?
- Do you see the Dart VM Service line in the native log?
Exercise
You changed a case "getUserName" branch in your Kotlin MethodChannel handler and also edited a widget in Dart. You press r in the terminal running flutter attach. The widget changes appear, but the channel still returns the old value. Why, and what do you do?
Show answer
Hot reload sends only Dart code to the VM. The Kotlin handler is native code that is already compiled and running in the host app, so it did not change. Rebuild and relaunch the host app from Android Studio, then run flutter attach again.
Exercise
A Flutter screen launched from your host app throws MissingPluginException for getUserName, but the same screen works when you run flutter run in the module. Name two causes to check.
Show answer
First, the channel name or method name may not match exactly between Dart and the native handler. Second, the handler may be registered on a different engine than the one running the screen, or it may be registered after Dart already called the method. Also, flutter run on the module uses its own hidden host, so the real host's handler is never involved there.