Flutter - Battery Level and State
Last Updated :
30 Nov, 2021
In this article, we will see how to fetch Battery level and its state using flutter. To fetch Battery level(percentage) and its state we use a package called battery plus package.
Important terms:
- Battery level - we see how much percent battery is remaining in mobile.
- Battery State - we see whether the state of the battery is charging, discharging or it's full.
Implementation:
Now we will practically see how to fetch battery level and check the state of the battery -
Step 1: Add dependencies to your pubspec.yaml file
Dart
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
battery_plus:
Step 2: Now, once we have added the dependencies into our flutter project, we need to import battery_plus.dart class.
Dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';
Step 3: To use the battery_plus class we need to create an instance of the Battery class. We had created a variable called percentage and we have kept its initial value to 0.
Step 4: Now we have created the method getBatteryPercentage() to check the battery percentage. In that method, we had initialized a variable level that stores the current value of the battery percentage. Then we had assigned the value to the percentage variable. Variable level returns a future type, so we had used async and await. Now we had created an init state and inside the init state we had called the getBatteryPercentage() method.
Dart
class _MyHomePageState extends State<MyHomePage> {
var battery = Battery();
int percentage = 0;
@override
void initState() {
super.initState();
// calling the method to display battery percentage
getBatteryPerentage();
}
// method created to display battery percent
void getBatteryPerentage() async {
final level = await battery.batteryLevel;
percentage = level;
setState(() {});
}
Step 5: In the build method we had created an Appbar in green color with text on it. Then we had created a column and inside that, we had displayed the battery percentage.
Dart
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('GeeksforGeeks', style: TextStyle(color: Colors.white),),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
// Displaying battery percentage
Text('Battery Percentage: $percentage', style: const TextStyle(fontSize: 24),)
],
),
),
);
}
Output:
Step 6: To get the latest update of our battery percentage again and again. We have used Timer. This timer will show the latest battery status after every 5 seconds. We can increase the timer or decrease it as per our need
Dart
class _MyHomePageState extends State<MyHomePage> {
var battery = Battery();
int percentage = 0;
late Timer timer;
@override
void initState() {
super.initState();
// calling the method to get battery state
getBatteryState();
// We have used timer to get the current status of
// battery percentage after every 5 seconds
Timer.periodic(const Duration(seconds: 5), (timer) {
getBatteryPerentage();
});
}
// method created to display battery percent
void getBatteryPerentage() async {
final level = await battery.batteryLevel;
percentage = level;
setState(() {});
}
Step 7: Now to get the status of our battery state whether the battery is in charging mode, discharging mode, or full. We had created a battery state of enum type and initially we had set the state to full. and as we go inside the Battery state to check its properties we see that the battery state is of enum class and has 4 types of features defined that help us know the current state of our battery.
Dart
class _MyHomePageState extends State<MyHomePage> {
var battery = Battery();
int percentage = 0;
late Timer timer;
// created a Batterystate of enum type
BatteryState batteryState = BatteryState.full;
late StreamSubscription streamSubscription;
This batterystate class contains 4 types of features that will help us to know the state of the battery.
Dart
// Indicates the current battery state.
enum BatteryState {
// The battery is completely full of energy.
full,
// The battery is currently storing energy.
charging,
// The battery is currently losing energy.
discharging,
// The state of the battery is unknown.
unknown
}
Step 8: Next we had created a getBatteryState() method. This method is created to check the current state of our battery and then update display it to the user. We had used here listen to the method that will store the current state of our battery and then we assign it to batteryState.
Dart
// method to know the state of the battery
void getBatteryState() {
streamSubscription = battery.onBatteryStateChanged.listen((state) {
batteryState = state;
setState(() {});
});
}
Then had called the method inside the initState()
Dart
@override
void initState() {
super.initState();
// calling the method to get battery state
getBatteryState();
Timer.periodic(const Duration(seconds: 5), (timer) {
getBatteryPerentage();
});
}
Step 9: At the final step we had created a custom widget called BatteryBuild() which accepts the battery state. In this widget, we had added different states of battery using switch case. Then called the custom widget BatteryBuild() in the build method
Dart
// Custom widget to add different states of battery
// ignore: non_constant_identifier_names
Widget BatteryBuild(BatteryState state) {
switch (state) {
case BatteryState.full:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_full,
size: 200,
color: Colors.green,
)),
);
case BatteryState.charging:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_charging_full,
size: 200,
color: Colors.blue,
)),
);
case BatteryState.discharging:
default:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_alert,
size: 200,
color: Colors.red,
)),
);
}
}
Full source code:
Dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var battery = Battery();
int percentage = 0;
late Timer timer;
// created a Batterystate of enum type
BatteryState batteryState = BatteryState.full;
late StreamSubscription streamSubscription;
@override
void initState() {
super.initState();
// calling the method to get battery state
getBatteryState();
// calling the method to get battery percentage
Timer.periodic(const Duration(seconds: 5), (timer) {
getBatteryPerentage();
});
}
// method created to display battery percent
void getBatteryPerentage() async {
final level = await battery.batteryLevel;
percentage = level;
setState(() {});
}
// method to know the state of the battery
void getBatteryState() {
streamSubscription = battery.onBatteryStateChanged.listen((state) {
batteryState = state;
setState(() {});
});
}
// Custom widget to add different states of battery
// ignore: non_constant_identifier_names
Widget BatteryBuild(BatteryState state) {
switch (state) {
// first case is for battery full state
// then it will show green in color
case BatteryState.full:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_full,
size: 200,
color: Colors.green,
)),
);
// Second case is when battery is charging
// then it will show blue in color
case BatteryState.charging:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_charging_full,
size: 200,
color: Colors.blue,
)),
);
// third case is when the battery is
// discharged then it will show red in color
case BatteryState.discharging:
default:
// ignore: sized_box_for_whitespace
return Container(
width: 200,
height: 200,
// ignore: prefer_const_constructors
child: (Icon(
Icons.battery_alert,
size: 200,
color: Colors.red,
)),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('GeeksforGeeks',
style: TextStyle(color: Colors.white),),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
// calling the custom widget
BatteryBuild(batteryState),
// Displaying battery percentage
Text('Battery Percentage: $percentage',
style: const TextStyle(fontSize: 24),)
],
),
),
);
}
}
Output:
Explanation -
- In step 9 we created a custom widget where we coded that if the mobile battery is charging then show us the battery in blue color. So currently my phone is not fully charged that's why we saw the battery in blue color.
- If our battery would have been 100% then the color would have changed to green
- If our battery would have been 0% then it would have been in red color. For more clarification see the below image.
Similar Reads
Flutter - Hide the Status Bar
StatusBar is located at the top of the Application, which basically shows the notification of the phones. Sample images are given below to get an idea about what we are going to do in this article. Before Hiding the status bar: Â After Hiding the status bar: Â If you see the difference between the i
2 min read
Flutter - Implement Status Alert
In Flutter, a "status alert" typically refers to a visual feedback mechanism that informs the user about the status or outcome of a certain operation or event. The status_alert package in Flutter is a third-party package that provides an easy way to create and display such status alerts. These alert
4 min read
Flutter vs Flutter 2
Overview :In this article, we will study the difference between Flutter 1 and Flutter 2. Flutter 1 was launched by Google in 2017. The reason behind launching this was so that the developer could use only a single code to develop applications for multiple platforms like Android, iOS, Linux, macOS. H
4 min read
Flutter - Send Data to Screen
Interaction with the UI is an integral part of any application. But more often than not, the information needs to be sent from one screen to another. For instance, say you need to pass data regarding a selected or tapped component of the UI to another route(i.e., page). In this article, we will expl
4 min read
Flutter - Difference Between ListView and List
Flutter is Googleâs Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), and Web apps from a single codebase. When building applications with Flutter everything is towards Widgets â the blocks with which the flutter apps are built. They are structural elements that ship with
4 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in A
4 min read
Flutter - Animated ScrollView
Creating an animated scroll view in Flutter involves using a combination of widgets and animation controllers to achieve the desired scrolling effect. Here we use Tween Animation to implement animation. In this article we are going to add an animation effect to a ScrollView A sample video is given b
5 min read
Flutter - Create Rating Star Bar
In the android application, you need to make a rating bar where user rate your craft. For example, GeeksforGeeks also make this feature for tutorials where users can give ratings to the tutorials. A sample video is given below to get an idea about what we are going to do in this article. How to Use?
3 min read
Flutter - Store Data in Hive Local Database
Hive is a data storage system on our phone where we can store data in boxes. We can store an integer, string, list of strings, Boolean, double, models, integers, etc., in Hive. Now, let us discuss where we can implement these. The first way we can use this is to save the user information user is log
12 min read
Flutter - Implement Light Mode and Dark Mode
In this article, we are working on the light theme and dark theme in the flutter application. A sample video is given below to get an idea about what we are going to do in this article. Step By Step Implementation Step 1: Create a New Project in Android Studio To set up Flutter Development on Androi
4 min read