📜  Flutter – 电池电量和状态

📅  最后修改于: 2022-05-13 01:54:32.196000             🧑  作者: Mango

Flutter – 电池电量和状态

在本文中,我们将了解如何使用flutter获取电池电量及其状态。为了获取电池电量(百分比)及其状态,我们使用了一个名为battery plus 包的包。

重要条款:

  • 电池电量- 我们看到手机中剩余的电量百分比。
  • 电池状态——我们查看电池的状态是充电、放电还是已满。

执行:

现在我们将实际了解如何获取电池电量并检查电池状态 -

第 1 步:将依赖项添加到pubspec.yaml文件

Dart
dependencies:
  flutter:
    sdk: flutter 
  cupertino_icons: ^1.0.2
  battery_plus:


Dart
import 'dart:async';
  
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';


Dart
class _MyHomePageState extends State {
  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(() {});
  }


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),)
            ],
        ),
      ),
    );
  }


Dart
class _MyHomePageState extends State {
  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(() {});
  }


Dart
class _MyHomePageState extends State {
  var battery = Battery();
  int percentage = 0;
  late Timer timer;
  
  // created a Batterystate of enum type
  BatteryState batteryState = BatteryState.full;
  late StreamSubscription streamSubscription;


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
}


Dart
// method to know the state of the battery
  void getBatteryState() {
    streamSubscription = battery.onBatteryStateChanged.listen((state) {
      batteryState = state;
  
      setState(() {});
    });
  }


Dart
@override
  void initState() {
    super.initState();
      
    // calling the method to get battery state
    getBatteryState();
  
    Timer.periodic(const Duration(seconds: 5), (timer) {
      getBatteryPerentage();
                                                          
    });                                                       
  }


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,
          )),
        );
    }
  }


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 createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  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),)
            ],
        ),
      ),
    );
  }
}


第2步:现在,一旦我们将依赖项添加到我们的flutter项目中,我们需要导入battery_plus。dart课。

Dart

import 'dart:async';
  
import 'package:flutter/material.dart';
import 'package:battery_plus/battery_plus.dart';

第 3 步:要使用battery_plus 类,我们需要创建 Battery 类的实例。我们创建了一个名为percent的变量,并将其初始值保持为0

第 4 步:现在我们创建了方法getBatteryPercentage()来检查电池百分比。在那个方法中,我们初始化了一个变量level来存储电池百分比的当前值。然后我们将值分配给百分比变量。变量 level 返回一个未来类型,所以我们使用了async 和 await 。现在我们已经创建了一个初始化状态,并且在初始化状态中我们调用了getBatteryPercentage()方法。

Dart

class _MyHomePageState extends State {
  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(() {});
  }

第 5 步:在 build 方法中,我们创建了一个带有文本的绿色Appbar 。然后我们创建了一个列,在其中显示了电池百分比。

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),)
            ],
        ),
      ),
    );
  }

输出:

第 6 步:一次又一次地获取我们电池百分比的最新更新。我们使用了Timer 。此计时器将在每 5 秒后显示最新的电池状态。我们可以根据需要增加或减少计时器

Dart

class _MyHomePageState extends State {
  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(() {});
  }

第 7 步:现在获取我们的电池状态状态,无论电池处于充电模式、放电模式还是充满。我们创建了一个枚举类型的电池状态,最初我们将状态设置为满。当我们进入电池状态检查它的属性时,我们看到电池状态是枚举类,并且定义了 4 种类型的特性来帮助我们了解电池的当前状态。

Dart

class _MyHomePageState extends State {
  var battery = Battery();
  int percentage = 0;
  late Timer timer;
  
  // created a Batterystate of enum type
  BatteryState batteryState = BatteryState.full;
  late StreamSubscription streamSubscription;
                                                 

电池状态类包含4 种类型的功能,可帮助我们了解电池的状态。

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
}

第 8 步:接下来我们创建了一个getBatteryState()方法。创建此方法是为了检查电池的当前状态,然后将其更新显示给用户。我们在这里使用了监听将存储电池当前状态的方法,然后将其分配给batteryState

Dart

// method to know the state of the battery
  void getBatteryState() {
    streamSubscription = battery.onBatteryStateChanged.listen((state) {
      batteryState = state;
  
      setState(() {});
    });
  }

然后调用了initState()里面的方法

Dart

@override
  void initState() {
    super.initState();
      
    // calling the method to get battery state
    getBatteryState();
  
    Timer.periodic(const Duration(seconds: 5), (timer) {
      getBatteryPerentage();
                                                          
    });                                                       
  }

第 9 步:在最后一步,我们创建了一个名为BatteryBuild()的自定义小部件,它接受电池状态。在这个小部件中,我们使用开关盒添加了不同的电池状态。然后在 build 方法中调用自定义小部件 BatteryBuild()

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,
          )),
        );
    }
  }

完整源代码:

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 createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  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),)
            ],
        ),
      ),
    );
  }
}

输出:

解释 -

  • 第 9 步中,我们创建了一个自定义小部件,我们在其中编写了代码,如果移动电池正在充电,则以蓝色显示电池。所以目前我的手机没有充满电,这就是为什么我们看到电池是蓝色的。
  • 如果我们的电池电量为100% ,那么颜色将变为绿色
  • 如果我们的电池电量为0% ,那么它将是红色的。有关更多说明,请参见下图