Open In App

Flutter – Battery Level and State

Last Updated : 30 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads