Flutter Battery level & state - battery plus

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial will learn how to get battery state & battery level (percentage) of a mobile device in flutter.

Flutter Battery plus package

By using battery plus package in flutter we can easily access various information about the battery life of mobile device.

This package will give us battery level & Battery state:

Battery Level i.e. will get how much is battery percentage.

Battery State i.e will get BatteryState is FULL, CHARGING, DISCHARGING.


When is battery level checking useful in app

Sometimes, some important action in your app like background updates, let’s say the user doesn’t have enought battery percentage then this can lead to issues in performing background task like updates & if the phone is turning off during the process.

Depending on the battery level you can also maximize/minimize the performance, while the battery level is high/low, this can be especially used in games so if mobile device battery life is low then you can turn down the game performance.

Battery Plus can also be used to test how much the battery is been consumed during your flutter app is running.


Video Tutorial

Let’s get started with implementation

Step 1: Add battery plus dependencies

open pubspec.yaml file & under dependencies section add battery_plus package

dependencies:
  battery_plus:

& hit pub get to download the package.

Step 2: import battery_plus.dart

Now, once you have added the dependencies into your flutter project to use it, you need to import battery_plus.dart class.

How to use it

Create instance of battery class

//instantiate it
var battery = Battery();

now you can use the battery instance object to get battery information.

Access battery percentage/level

battery.batterylevel

Get State of Battery

The below code will be listening to any changes in BatteryState.

It will keep track of batteryState, Weather the mobile is in charging, discharged or battery full. There is a callback method that return enum values:

  1. BatteryState.charging.
  2. BatteryState.discharging.
  3. BatteryState.full.
battery.onBatteryStateChanged.listen((batteryState) {
//here batteryState is Enum that can return this values:
//BatteryState.charging.
// BatteryState.discharging.
// BatteryState.full.
});

Complete Source – Flutter Battery Plus Example

In this flutter example, we willl fetch battery percentage level & also keep track, when mobile is into charging & when is removed from charging(discharging) and it will also alert or update you when battery is FULL.

main.dart

import 'dart:async';

import 'package:battery_plus/battery_plus.dart';
import 'package:flutter/material.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: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var battery = Battery();
  int level = 100;
  BatteryState batteryState = BatteryState.full;
  late Timer timer;
  late StreamSubscription streamSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBatteryPercentage();
    getBatteryState();
    timer = Timer.periodic(Duration(seconds: 5), (timer) {
      getBatteryPercentage();
    });
  }

  void getBatteryPercentage() async {
    final batteryLevel = await battery.batteryLevel;

    this.level = batteryLevel;

    setState(() {});
  }

  void getBatteryState() {
    streamSubscription = battery.onBatteryStateChanged.listen((state) {
      setState(() {
        this.batteryState = state;
      });
    });
  }

  @override
  void dispose() {
    streamSubscription.cancel();
    timer.cancel();
  }

  Widget BuildBattery(BatteryState state) {
    switch (state) {
      case BatteryState.full:
        return Container(
          child: Icon(
            Icons.battery_full,
            size: 200,
            color: Colors.green,
          ),
          width: 200,
          height: 200,
        );
      case BatteryState.charging:
        return Container(
          child:
              Icon(Icons.battery_charging_full, size: 200, color: Colors.blue),
          width: 200,
          height: 200,
        );
      case BatteryState.discharging:

      default:
        return Container(
          child: Icon(Icons.battery_alert, size: 200, color: Colors.grey),
          width: 200,
          height: 200,
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              BuildBattery(batteryState),
              Text(
                '${level} %',
                style: TextStyle(color: Colors.black, fontSize: 25),
              ),
            ],
          ),
        ),
      ),
    );
  }
}