android_battery_level_plus 0.0.1
android_battery_level_plus: ^0.0.1 copied to clipboard
A Flutter plugin to access the device's current battery level on Android.
example/lib/android_battery_level_plus_example.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:android_battery_level_plus/battery_plugin.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _batteryLevel = 'Unknown';
final _batteryPlugin = BatteryPlugin();
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String batteryLevel;
// Platform messages may fail, so we use a try/catch PlatformException.
// We also handle the message potentially returning null.
try {
final level = await _batteryPlugin.getBatteryLevel();
// ignore: unnecessary_null_comparison, dead_code
batteryLevel = level != null ? level.toString() : 'Unknown';
} on PlatformException {
batteryLevel = 'Failed to get battery level.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_batteryLevel = batteryLevel;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Battery Plugin')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Battery Level: $_batteryLevel%',
style: const TextStyle(fontSize: 24),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: initPlatformState,
child: const Text('Refresh Battery Level'),
),
],
),
),
),
);
}
}