import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class BatteryLevelScreen extends StatefulWidget {
@override
State<BatteryLevelScreen> createState() => _BatteryLevelScreenState();
}
class _BatteryLevelScreenState extends State<BatteryLevelScreen> {
static const platform = MethodChannel('samples.flutter.dev/battery');
String _batteryLevel = 'Battery Level: ?%';
Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery Level: $result%';
} on PlatformException {
batteryLevel = 'Failed to get battery level.';
}
if (!mounted) return;
setState(() {
_batteryLevel = batteryLevel;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Battery Level Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_batteryLevel, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _getBatteryLevel,
child: const Text('Get Battery Level'),
),
],
),
),
);
}
}
This app uses a MethodChannel to communicate with native platform code to get the battery level.
We define a channel named samples.flutter.dev/battery. When the user taps the button, _getBatteryLevel calls invokeMethod('getBatteryLevel') which asks the native code for the battery percentage.
If successful, it updates the text to show the battery level. If it fails, it shows an error message.
This example teaches how Flutter apps can talk to native code to access device features not directly available in Flutter.