Sub topic 9
Running the plugin from the example app
This chapter assumes you have generated the battery_info plugin and written its Dart, Kotlin and Swift code in the earlier chapters. You also need a working Flutter toolchain, an Android emulator or device, and an iOS simulator or device with Xcode set up.
Why the example app exists
The example/ directory is a normal Flutter app that depends on your plugin. It is the only place where the Dart code, the platform channel and the native code run together. Unit tests with a mocked channel cannot show that the Kotlin and Swift sides agree with the Dart side. The example app can.
It also becomes your documentation. pub.dev shows the contents of example/ on the package page, so a clear example app is useful to users.
How the example app finds the plugin
Open example/pubspec.yaml. The generator added a path dependency on the parent directory:
name: battery_info_example
description: Demonstrates how to use the battery_info plugin.
publish_to: 'none'
environment:
sdk: ^3.0.0
dependencies:
flutter:
sdk: flutter
battery_info:
path: ../Because the dependency is a path, the Flutter tool reads the flutter.plugin.platforms section of the plugin's pubspec.yaml. It then generates registration code in the example app's native projects. On Android this is GeneratedPluginRegistrant.java. On iOS it is GeneratedPluginRegistrant.m. Both files call your plugin class at startup. You never edit them, and the tool rewrites them whenever you run flutter pub get.
Writing a useful example
Replace example/lib/main.dart with a small screen that exercises the API and shows both success and failure.
import 'package:battery_info/battery_info.dart';
import 'package:flutter/material.dart';
void main() => runApp(const ExampleApp());
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: BatteryScreen());
}
}
class BatteryScreen extends StatefulWidget {
const BatteryScreen({super.key});
@override
State<BatteryScreen> createState() => _BatteryScreenState();
}
class _BatteryScreenState extends State<BatteryScreen> {
final BatteryInfo _battery = BatteryInfo();
String _status = 'Press the button to read the battery level.';
Future<void> _read() async {
try {
final int level = await _battery.getBatteryLevel();
setState(() => _status = 'Battery level: $level%');
} on BatteryInfoException catch (e) {
setState(() => _status = 'Failed: ${e.code} (${e.message})');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('battery_info example')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_status),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _read,
child: const Text('Read battery level'),
),
],
),
),
);
}
}The example catches BatteryInfoException, not PlatformException. This shows users the public contract and confirms that your wrapper from the error-handling chapter works end to end.
Running on each platform
List the available devices, then run on a specific one:
cd battery_info/example
flutter devices
flutter run -d <device-id>The first build is slow. On Android, Gradle downloads dependencies and compiles your plugin as a library module. On iOS, CocoaPods installs the plugin as a development pod, and Xcode then builds it. Later builds are incremental.
Expect different results on the two platforms:
| Environment | Typical result |
|---|---|
| Android emulator | A level such as 100 or whatever the emulator's virtual battery is set to |
| Android device | The real level |
| iOS simulator | `UNAVAILABLE`, because `UIDevice.batteryLevel` returns -1 on the simulator |
| iOS device | The real level |
The iOS simulator result is not a bug. It confirms that your FlutterError path works. Test the success path on a real iPhone.
What hot reload does and does not cover
Hot reload and hot restart rebuild only the Dart code. They do not recompile Kotlin or Swift. This leads to a common source of confusion.
- Dart changes in the plugin's
lib/or the example'slib/are picked up by hot reload. - Changes to Kotlin, Swift, Gradle files or podspecs need a full stop and
flutter run. - After you add a new platform class or change
pluginClassinpubspec.yaml, runflutter cleanif the new class is not picked up, thenflutter run.
Debugging the native side
Dart breakpoints work in your IDE as usual. For native code you have two options.
Logging
Logging is the quickest way to see what happens. Add a line to the Kotlin handler:
android.util.Log.d("BatteryInfo", "onMethodCall: ${call.method}")Read it with adb logcat -s BatteryInfo, or in the Logcat window in Android Studio. On iOS, call NSLog("BatteryInfo handle: %@", call.method) in Swift. The output appears in the Xcode console and in flutter run.
Native debuggers
For breakpoints in native code, open the native project that contains your plugin.
- For Android, open
example/androidin Android Studio. Your plugin appears as a module named after the package, and you can set breakpoints inBatteryInfoPlugin.kt. - Start the app with
flutter runor from Android Studio, then choose Run > Attach Debugger to Android Process. - For iOS, open
example/ios/Runner.xcworkspacein Xcode. Always open the.xcworkspace, not the.xcodeproj, or CocoaPods targets are missing. - Your Swift file is under Pods > Development Pods > battery_info. Set a breakpoint there and run from Xcode.
- To debug Dart at the same time, run
flutter attachin a terminal while the app runs from Xcode.
Common build failures
pod installfails or reports a deployment target mismatch. Compare the iOS platform version inios/battery_info.podspecwithexample/ios/Podfile. Raise the Podfile value or lower the podspec value so they agree. Then runflutter cleanand try again.- Gradle reports a
minSdkconflict. Set the same minimum SDK inandroid/build.gradleand in the example app's Android configuration. - Swift cannot find
Flutter. You probably opened the.xcodeproj. Close it and open the.xcworkspace. - Kotlin changes do not appear. Run
flutter runagain, not a hot reload. If that does not work, stop the app, deleteexample/build, and rerun.
Using the example for release checks
Before publishing, run the example in release mode on a real device for each platform:
flutter run --release -d <device-id>Release builds apply code shrinking on Android. If your plugin uses reflection or a native library that needs keep rules, problems appear only in this mode.
Exercise
You change a string in BatteryInfoPlugin.kt and press hot reload in the running example app. The behavior does not change. Why, and what should you do?
Show answer
Hot reload only recompiles and injects Dart code. Kotlin is compiled by Gradle into the installed app, so the running app still contains the old native code. Stop the app and run flutter run again, which rebuilds the Android project with your change.
Exercise
On the iOS simulator the example app shows Failed: UNAVAILABLE (Battery level not available.). Is the plugin broken? How would you check the success path?
Show answer
No. The simulator has no battery, so UIDevice.current.batteryLevel returns -1 and the Swift code correctly returns a FlutterError, which Dart turns into a BatteryInfoException. To check the success path, run the example on a physical iPhone, or on an Android emulator or device.