Last active
November 27, 2024 06:58
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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