battery_plugin_ab_22oct24 0.0.1 battery_plugin_ab_22oct24: ^0.0.1 copied to clipboard
battery plugin by Abhijeet Gole.
import 'package:flutter/material.dart';
import 'package:battery_plugin/battery_plugin.dart';
import 'package:flutter/services.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 battery level.';
@override
void initState() {
super.initState();
_getBatteryLevel();
}
// Function to get the battery level
Future<void> _getBatteryLevel() async {
int? batteryLevel;
try {
batteryLevel = await BatteryPlugin.getBatteryLevel();
} on PlatformException {
batteryLevel = null;
}
setState(() {
_batteryLevel = batteryLevel != null ? 'Battery level: $batteryLevel%' : 'Failed to get battery level.';
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Battery Plugin Example'),
),
body: Center(
child: Text(_batteryLevel),
),
floatingActionButton: FloatingActionButton(
onPressed: _getBatteryLevel,
child: const Icon(Icons.battery_charging_full),
),
),
);
}
}