As we continue to learn Flutter App development for both iOS and Android, we want to look at Battery: how to get access to various battery information in your app. This is important because you may wish for example to only allow performing some tasks based on battery level,if you are creating a smart app.
We will use the now recommended battery_plus
package.
battery_plus
A flutter package to access various information about the battery of the device the app is running.
This plugins supports:
- Android
- iOS
- MacOS
- Web
- Linux
- Windows
Step 1: Install it
Start by installing the package. Declare it as a dependency in your pubspec.yaml
:
dependencies:
battery_plus: ^2.0.1
Then sync or flutter pub get
.
Alternatively you can install it from the commandline:
$ flutter pub add battery_plus
Step 2: Write Code
Start by importing it:
import 'package:battery_plus/battery_plus.dart';
Then instantiate it:
// Instantiate it
var battery = Battery();
You can then print the battery level:
// Access current battery level
print(await battery.batteryLevel);
You can also listen to battery state changes:
battery.onBatteryStateChanged.listen((BatteryState state) {
// Do something with new state
});
Full Example
Here is a full example of how to use the battery package:
main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Battery _battery = Battery();
BatteryState? _batteryState;
StreamSubscription<BatteryState>? _batteryStateSubscription;
@override
void initState() {
super.initState();
_batteryStateSubscription =
_battery.onBatteryStateChanged.listen((BatteryState state) {
setState(() {
_batteryState = state;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$_batteryState'),
ElevatedButton(
onPressed: () async {
final batteryLevel = await _battery.batteryLevel;
// ignore: unawaited_futures
showDialog<void>(
context: context,
builder: (_) => AlertDialog(
content: Text('Battery: $batteryLevel%'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('OK'),
)
],
),
);
},
child: const Text('Get battery level'),
),
ElevatedButton(
onPressed: () async {
final isInPowerSaveMode = await _battery.isInBatterySaveMode;
// ignore: unawaited_futures
showDialog<void>(
context: context,
builder: (_) => AlertDialog(
content: Text('Is on low power mode: $isInPowerSaveMode'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('OK'),
)
],
),
);
},
child: const Text('Is on low power mode'))
],
),
),
);
}
@override
void dispose() {
super.dispose();
if (_batteryStateSubscription != null) {
_batteryStateSubscription!.cancel();
}
}
}
Reference
Below are the code links:
Number | Link |
---|---|
1. | Download Example |
2. | Read more |
Example 2: Flutter battery_plus Example
Let's look at the second Flutter BatteryPlus Example.
Step 1: Create Project
Start by creating an empty Flutter Project.
Step 2: Install battery_plus
In your pubspec.yaml
add battery_plus
as a dependency, as follows:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
battery_plus:
flutter pub get
or sync to fetch it.
Step 3: Write Code
Start by adding imports including the async
, material
and battery_plus
packages:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';
Define the main()
function:
void main() {
runApp(const MyApp());
}
Create the MyApp
class by extending the StatelessWidget
class:
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(),
);
}
}
Extend the StatefulWidget
to create the MyHomePage
class:
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
Now come create the _MyHomepageState
class:
class _MyHomePageState extends State<MyHomePage> {
Instantiate the Battery
and define other instance fields:
var battery = Battery();
int percentage = 0;
late Timer timer;
BatteryState batteryState = BatteryState.full;
late StreamSubscription streamSubscription;
Get battery percentage using this function:
void getBatteryPercentage() async {
final level = await battery.batteryLevel;
percentage = level;
setState(() {});
}
Then battery state:
void getBatteryState() async {
streamSubscription = battery.onBatteryStateChanged.listen((state) {
batteryState = state;
setState(() {});
});
}
below is the full code:
main.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: 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 percentage = 0;
late Timer timer;
BatteryState batteryState = BatteryState.full;
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 level = await battery.batteryLevel;
percentage = level;
setState(() {});
}
void getBatteryState() async {
streamSubscription = battery.onBatteryStateChanged.listen((state) {
batteryState = state;
setState(() {});
});
}
Widget Buildbattery(BatteryState state) {
switch (state) {
case BatteryState.full:
return Container(
width: 200,
height: 200,
child: Icon(
Icons.battery_full,
size: 200,
color: Colors.green,
),
);
case BatteryState.charging:
return Container(
width: 200,
height: 200,
child: Icon(
Icons.battery_charging_full,
size: 200,
color: Colors.blue,
),
);
case BatteryState.discharging:
default:
return Container(
width: 200,
height: 200,
child: Icon(
Icons.battery_alert,
size: 200,
color: Colors.deepOrangeAccent,
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Buildbattery(batteryState),
Text(
'Battery Percentage: ${percentage}',
style: TextStyle(fontSize: 25),
)
],
),
),
);
}
}
Reference
Download the code below:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |