Skip to content

Instantly share code, notes, and snippets.

@NigamTechify185
Last active November 27, 2024 06:58
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class BatteryLevel extends StatefulWidget {
@override
_BatteryLevelState createState() => _BatteryLevelState();
}
class _BatteryLevelState extends State<BatteryLevel> {
static const platform = MethodChannel('battery');
String batteryLevel = 'Unknown';
Future<void> getBatteryLevel() async {
try {
final int result = await platform.invokeMethod('getBatteryLevel');
setState(() {
batteryLevel = '$result%';
});
} on PlatformException catch (e) {
setState(() {
batteryLevel = "Failed to get battery level: '${e.message}'.";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Battery Level')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Battery Level: $batteryLevel'),
ElevatedButton(
child: Text('Get Battery Level'),
onPressed: getBatteryLevel,
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment