Battery Details in Flutter: battery_plus package

We are going to explore the package battery_plus by fluttercommunity which allows developers to access the state of the battery of the device. This package is compatible with all the platforms and can provide real-time data. So let's start building the app.

The final result would contain the battery state and the percentage

Install the package

flutter pub add battery_plus

Import the package

import 'package:battery_plus/battery_plus.dart';

Get the battery details

The package provides us with all the required functionalities.

  1. Battery().batteryLevel: This method returns the current battery level as a percentage, ranging from 0 to 100.

  2. Battery().onBatteryStateChanged: This method returns a Stream that emits battery state changes as they occur. The stream emits BatteryState objects.

  3. Battery().batteryState: This method returns the current battery state, which can be one of the following values:

    • BatteryState.full: The battery is fully charged.

    • BatteryState.charging: The battery is currently charging.

    • BatteryState.discharging: The battery is currently discharging.

    • BatteryState.unknown: The battery state is unknown.

So we are accessing the state and the value of the battery as follows:

BatteryState _batteryState = BatteryState.unknown;
int level = 0;
void getBatteryStateAndLevel() async {
  // Get battery level.
  Battery().onBatteryStateChanged.listen((BatteryState state) {
    setState(() {
      _batteryState = state;
    });

    Battery().batteryLevel.then((value) {
      setState(() {
        level = value;
      });
    });
  });
}

UI of the application

Here is the UI structure

Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget>[
      const Text(
        'Battery Details',
        style: TextStyle(fontSize: 20),
      ),
      Text(
        'Battery Level: $level%',
        style: const TextStyle(fontSize: 20),
      ),
      Text(
        'Battery State: ${_batteryState.name}',
        style: const TextStyle(fontSize: 20),
      ),
      ElevatedButton(
        onPressed: () {
          getBatteryStateAndLevel();
        },
        child: const Text('Get Battery State and Level'),
      ),
    ],
  ),
),

Hence the final output is as follows:

Here is the full code

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: const BatteryDetails(),
    );
  }
}

class BatteryDetails extends StatefulWidget {
  const BatteryDetails({super.key});

  @override
  State<BatteryDetails> createState() => _BatteryDetailsState();
}

class _BatteryDetailsState extends State<BatteryDetails> {
  BatteryState _batteryState = BatteryState.unknown;
  int level = 0;
  void getBatteryStateAndLevel() async {
    // Get battery level.
    Battery().onBatteryStateChanged.listen((BatteryState state) {
      setState(() {
        _batteryState = state;
      });

      Battery().batteryLevel.then((value) {
        setState(() {
          level = value;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Battery Details - allaboutflutter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            const Text(
              'Battery Details',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              'Battery Level: $level%',
              style: const TextStyle(fontSize: 20),
            ),
            Text(
              'Battery State: ${_batteryState.name}',
              style: const TextStyle(fontSize: 20),
            ),
            ElevatedButton(
              onPressed: () {
                getBatteryStateAndLevel();
              },
              child: const Text('Get Battery State and Level'),
            ),
          ],
        ),
      ),
    );
  }
}

See you in the next tutorial.

Did you find this article valuable?

Support All About Flutter | Flutter and Dart by becoming a sponsor. Any amount is appreciated!