How to Listen Charging Status and Battery Level Change in Flutter App

In this example, we are going to show the best way to listen to battery level percentage, charging status, or any changes regarding battery information. For example, if you want to make an app that executes any code block automatically whenever the charger is connected to the device. See the example below for more details. 

First, you need to add battery_info Flutter package in your dependency by adding the following lines in pubspec.yaml file. 

dependencies:
  flutter:
    sdk: flutter
  battery_info: ^1.0.7

This Package can get the following information or listen from Android and iOS:

Android iOS
  • Battery Level
  • Charging Status
  • Charge Time Remaining
  • Current Average
  • Current Now
  • Health
  • Plugged Status
  • Battery Presence
  • Scale
  • Remaining Energy
  • Technology
  • Temperature
  • Voltage
  • Battery Level
  • Charging Status

Import package file in your script. 

import 'package:battery_info/model/android_battery_info.dart';
//import for android
import 'package:battery_info/model/iso_battery_info.dart';
//import for iOS

 BatteryInfoPlugin().androidBatteryInfoStream.listen((AndroidBatteryInfo batteryInfo) { 
     //add listiner to update values if there is changes
     //you can get all kinds of information from variable batteryinfo.
});

import 'package:battery_info/battery_info_plugin.dart';
import 'package:battery_info/enums/charging_status.dart';
import 'package:battery_info/model/android_battery_info.dart';
//import for android
import 'package:battery_info/model/iso_battery_info.dart';
//import for iOS
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState(){
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {

  String batterylevel = "";
  ChargingStatus chargingstatus = ChargingStatus.Discharging; //by default, it is not charging

  @override
  void initState() {
    
     AndroidBatteryInfo infoandroid = AndroidBatteryInfo();
     //IosBatteryInfo infoios = IosBatteryInfo(); use for iOS
     
     Future.delayed(Duration.zero, () async { //there is async (await) execution inside it
        infoandroid = await BatteryInfoPlugin().androidBatteryInfo;
        // infoios = await BatteryInfoPlugin().iosBatteryInfo;  for iOS
        
        batterylevel = infoandroid.batteryLevel.toString();
        chargingstatus = infoandroid.chargingStatus;
        setState(() {
          //refresh UI
        });
     });

     BatteryInfoPlugin().androidBatteryInfoStream.listen((AndroidBatteryInfo batteryInfo) { 
     //add listiner to update values if there is changes
          infoandroid = batteryInfo;
          batterylevel = infoandroid.batteryLevel.toString();
          chargingstatus = infoandroid.chargingStatus;
          setState(() {
            //refresh UI
          });
     });

    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold( 
            appBar: AppBar( 
              title: Text("Charging Info"),
              backgroundColor: Colors.redAccent
            ),
            
            body: Container( 
              color: chargingstatus == ChargingStatus.Charging ? Colors.greenAccent[100]:Colors.redAccent,
              alignment: Alignment.center,
              padding: EdgeInsets.all(20),
              margin: EdgeInsets.all(20),
              height:120,
              child: Column( 
                children: [
                  Text("Battery Level: $batterylevel %", style: TextStyle(fontSize: 20),),
                  Text(chargingstatus.toString(), style: TextStyle(fontSize: 20)), 
                  //values: ChargingStatus.charging, discharging, full, unkown
                  Text("Green = Charging \n Red = Not Charging")
                ],
              )
            )
        ),
    );
  }
}

Charging Not Charging

This screen color changes automatically whenever Charger is connected or disconnected.

In this way, you can listen to battery status, charging status changes in Flutter App.

No any Comments on this Article


Please Wait...