import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: PlatformChannelDemo(),
);
}
}
class PlatformChannelDemo extends StatefulWidget {
const PlatformChannelDemo({super.key});
@override
State<PlatformChannelDemo> createState() => _PlatformChannelDemoState();
}
class _PlatformChannelDemoState extends State<PlatformChannelDemo> {
static const platform = MethodChannel('samples.flutter.dev/battery');
String _batteryLevel = '?';
Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = result.toString();
} on PlatformException {
batteryLevel = 'Unknown';
}
if (!mounted) return;
setState(() {
_batteryLevel = batteryLevel;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Platform Channel Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Battery Level: $_batteryLevel%'),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _getBatteryLevel,
child: const Text('Get Battery Level'),
),
],
),
),
);
}
}
This Flutter app uses a MethodChannel named samples.flutter.dev/battery to communicate with native code.
When the user taps the 'Get Battery Level' button, the app calls invokeMethod('getBatteryLevel') on the channel. This sends a message to the native platform (Android or iOS) to run native code that returns the current battery level as an integer.
The app waits asynchronously for the result. If successful, it updates the displayed battery level. If there is an error (for example, native code not implemented), it shows 'Unknown'.
This shows how platform channels bridge Flutter and native code, allowing Flutter apps to use device features not available directly in Flutter.