How to Debug Flutter Plugins on PlatformChannel

debugging

flutter

Flutter is a cross-platform framework that relies on native code to offer advanced features.
On mobile platforms, it uses Platform channels to send messages between Dart and the native platform (iOS or Android).

I recently developed a plugin at Bam and needed to debug native code easily. In this article I will present how to debug Kotlin code for Android and Swift code for iOS. It will also lead you to use the correct tools to have full autocomplete while developing a Flutter plugin (who likes to wait runtime to see a missing bracket?).

Prerequisites

To follow the same folder structure, you can generate a sample plugin folder with this command:

flutter create --template=plugin --platforms=android,ios bam_plugin

Note that if you’re creating a new plugin, you should now use the federated folder structure.

If you’re running the example you should have this simple app.

app_screenshot

Dart

The first thing to know to properly debug a Flutter plugin, is to debug the Dart code. If you’re using VSCode or Android Studio, it is straightforward.

In the lib folder, you can just click on the left end of a line to add a breakpoint.

breakpoint_dart

Upon launching the application with debugging (F5 on VSCode), the app will stop when the Platform channel is invoked. But you don’t have access to the native code execution. In order to see the logs for the native part, you will have to open directly the Android or the iOS project.

Android

In order to debug the Android side of the plugin, you should first open the example/android folder with Android Studio.
You should have the following folder structure:

folder_android

Since bam_plugin is a dependency of your Android project it will directly show under your app. Here, you will be able to code your plugin with all the autocomplete features you would be missing in VSCode.

You can also add a breakpoint in the BamPlugin.kotlin file and debug directly in Android Studio.

breakpoint_android

iOS

In order to debug the iOS side of the plugin, you will need to open the example/ios with XCode.

Note that you can directly open the correct folder with this command:

xed example/ios

It will open the xcworkspace if Cocoapods is available, and the xcodeproj otherwise.

You can then expand a lot of folders to reach your plugin files and start editing here with full autocomplete.

folder_ios

You can here add a breakpoint to your BamPlugin.swift file and start debugging your Platform channel calls.

breakpoint_ios

Conclusion

Even if at first, through VSCode, you couldn’t use any of the debugging feature, you should now be able to develop a native plugin more efficiently. If you have any comment or suggestion, don’t hesitate to drop a message @BeGuillaume on Twitter.

Let me know if you’re interested in other tutorials covering other platforms.