Flutter电池状态显示插件battery_indicator的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter电池状态显示插件battery_indicator的使用

介绍

flutter_battery_indicator 是一个用于显示电池状态的Flutter插件。你可以使用手机的电池值来显示,也可以提供自己的电池级别值。该插件支持多种样式和自定义选项,如颜色、大小、比例等。

battery_indicator.gif

示例截图

以下是使用该插件的示例截图:

  • 原生Flutter示例 1.jpeg 2.jpeg

  • 使用GetX的示例 1.jpeg 2.jpeg

使用方法

1. 添加依赖

pubspec.yaml 文件中添加 battery_indicator 依赖:

dependencies:
  battery_indicator: ^0.1.0
2. 使用手机电池值显示

你可以在布局中直接使用 BatteryIndicator 小部件来显示手机的电池状态。以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:battery_indicator/battery_indicator.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _styleIndex = 0;
  var _colorful = true;
  var _showPercentSlide = true;
  var _showPercentNum = false;
  var _size = 18.0;
  var _ratio = 3.0;
  Color _color = Colors.blue;

  // 颜色选择器
  Widget getColorSelector(Color color) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _color = color;
        });
      },
      child: CircleAvatar(
        backgroundColor: color,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              width: 200.0,
              height: 100.0,
              child: Center(
                child: BatteryIndicator(
                  style: BatteryIndicatorStyle.values[_styleIndex], // 电池样式
                  colorful: _colorful, // 是否多彩
                  showPercentNum: _showPercentNum, // 是否显示百分比数字
                  mainColor: _color, // 主颜色
                  size: _size, // 大小
                  ratio: _ratio, // 比例
                  showPercentSlide: _showPercentSlide, // 是否显示百分比滑块
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  const Text('颜色:'),
                  getColorSelector(Colors.blue),
                  getColorSelector(Colors.red),
                  getColorSelector(Colors.black),
                  getColorSelector(Colors.grey),
                  getColorSelector(Colors.yellow),
                  getColorSelector(Colors.green),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  const Text('大小:'),
                  Expanded(
                    child: Slider(
                      min: 8.0,
                      max: 48.0,
                      divisions: 300,
                      label: _size.toStringAsFixed(1),
                      value: _size,
                      onChanged: (val) {
                        setState(() {
                          _size = val;
                        });
                      },
                    ),
                  ),
                  const Text('比例:'),
                  Expanded(
                    child: Slider(
                      min: 1.0,
                      max: 4.0,
                      divisions: 30,
                      label: _ratio.toStringAsFixed(1),
                      value: _ratio,
                      onChanged: (val) {
                        setState(() {
                          _ratio = val;
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                const Text('多彩:'),
                Checkbox(
                  value: _colorful,
                  onChanged: (val) {
                    setState(() {
                      _colorful = val ?? _colorful;
                    });
                  },
                ),
                const Text('显示百分比数字:'),
                Checkbox(
                  value: _showPercentNum,
                  onChanged: (val) {
                    setState(() {
                      _showPercentNum = val ?? _showPercentNum;
                    });
                  },
                ),
                const Text('显示百分比滑块:'),
                Checkbox(
                  value: _showPercentSlide,
                  onChanged: (val) {
                    setState(() {
                      _showPercentSlide = val ?? _showPercentSlide;
                    });
                  },
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                const Text('样式:'),
                DropdownButton(
                  value: _styleIndex,
                  items: [
                    const DropdownMenuItem(
                      value: 0,
                      child: Text('扁平化'),
                    ),
                    const DropdownMenuItem(
                      value: 1,
                      child: Text('拟物化'),
                    ),
                  ],
                  onChanged: (val) {
                    setState(() {
                      _styleIndex = val as int;
                    });
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
3. 提供自定义电池值

你还可以通过 batteryFromPhonebatteryLevel 参数来提供自定义的电池值。以下是一个示例代码:

import 'package:flutter/material.dart';
import 'package:battery_indicator/battery_indicator.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int bat = 34; // 自定义电池值

  void increment() {
    setState(() {
      if (bat < 100) {
        bat++;
      }
    });
  }

  void decrement() {
    setState(() {
      if (bat > 0) {
        bat--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            BatteryIndicator(
              batteryFromPhone: false, // 不使用手机电池值
              batteryLevel: bat, // 自定义电池值
              style: BatteryIndicatorStyle.values[0], // 电池样式
              colorful: true, // 是否多彩
              showPercentNum: true, // 是否显示百分比数字
              mainColor: Colors.blue, // 主颜色
              size: 35.0, // 大小
              ratio: 6.0, // 比例
              showPercentSlide: true, // 是否显示百分比滑块
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: increment,
              child: const Text('增加电池值'),
            ),
            ElevatedButton(
              onPressed: decrement,
              child: const Text('减少电池值'),
            ),
          ],
        ),
      ),
    );
  }
}
4. 使用GetX管理电池值

如果你使用 GetX 状态管理库,可以通过 ObxRxInt 来管理电池值。以下是一个示例代码:

home_view.dart

import 'package:flutter/material.dart';
import 'package:battery_indicator/battery_indicator.dart';
import 'package:get/get.dart';

class HomeView extends StatelessWidget {
  final HomeController controller = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Battery Indicator with GetX"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(() => BatteryIndicator(
              batteryFromPhone: false,
              batteryLevel: controller.bat.value,
              style: controller.myStyle,
              colorful: controller.colorful,
              showPercentNum: controller.showPercentNum,
              mainColor: controller.color,
              size: controller.size,
              ratio: controller.ratio,
              showPercentSlide: controller.showPercentSlide,
            )),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: controller.increment,
              child: Text('增加电池值'),
            ),
            ElevatedButton(
              onPressed: controller.decrement,
              child: Text('减少电池值'),
            ),
          ],
        ),
      ),
    );
  }
}

home_controller.dart

import 'package:get/get.dart';

class HomeController extends GetxController {
  // 0: 扁平化, 1: 拟物化
  BatteryIndicatorStyle myStyle = BatteryIndicatorStyle.values[0];

  var colorful = true.obs;
  var showPercentSlide = true.obs;
  var showPercentNum = true.obs;
  var size = 35.0.obs;
  var ratio = 6.0.obs;
  Color color = Colors.blue;
  RxInt bat = 35.obs;

  void increment() {
    if (bat.value < 100) {
      bat.value++;
    }
  }

  void decrement() {
    if (bat.value > 0) {
      bat.value--;
    }
  }
}

更多关于Flutter电池状态显示插件battery_indicator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter电池状态显示插件battery_indicator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用battery_indicator插件来显示电池状态的代码示例。这个插件可以帮助你获取设备的电池状态信息,并在UI中展示。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加battery_indicator依赖:

dependencies:
  flutter:
    sdk: flutter
  battery_indicator: ^latest_version  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 导入插件

在你的Dart文件中导入battery_indicator插件:

import 'package:flutter/material.dart';
import 'package:battery_indicator/battery_indicator.dart';

3. 使用插件获取电池状态并显示

下面是一个完整的示例,展示了如何使用battery_indicator插件获取电池状态并在UI中显示:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Battery Indicator Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BatteryStatusScreen(),
    );
  }
}

class BatteryStatusScreen extends StatefulWidget {
  @override
  _BatteryStatusScreenState createState() => _BatteryStatusScreenState();
}

class _BatteryStatusScreenState extends State<BatteryStatusScreen> {
  BatteryState? _batteryState;

  @override
  void initState() {
    super.initState();
    _getBatteryState();
  }

  Future<void> _getBatteryState() async {
    BatteryState batteryState = await BatteryIndicator.batteryState;
    setState(() {
      _batteryState = batteryState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Battery Status'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (_batteryState != null)
              Text(
                'Battery Level: ${_batteryState!.level.toStringAsFixed(1)}%',
                style: TextStyle(fontSize: 24),
              ),
            SizedBox(height: 20),
            if (_batteryState != null)
              BatteryIndicator(
                batteryState: _batteryState!,
                builder: (context, level, isCharging) {
                  return Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black),
                      shape: BoxShape.circle,
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: isCharging
                          ? Icon(
                              Icons.battery_charging_full,
                              color: Colors.green,
                            )
                          : Icon(
                              Icons.battery_full,
                              color: _getBatteryColor(level),
                            ),
                    ),
                  );
                },
              ),
          ],
        ),
      ),
    );
  }

  Color _getBatteryColor(double level) {
    if (level >= 0.75) {
      return Colors.green;
    } else if (level >= 0.25) {
      return Colors.orange;
    } else {
      return Colors.red;
    }
  }
}

解释

  1. 依赖添加:在pubspec.yaml中添加battery_indicator依赖。
  2. 导入插件:在Dart文件中导入battery_indicator
  3. 获取电池状态:在initState方法中调用BatteryIndicator.batteryState来获取电池状态,并使用setState更新状态。
  4. 显示电池状态:使用Text组件显示电池电量百分比,并使用BatteryIndicator组件自定义电池图标显示。_getBatteryColor方法根据电量百分比返回不同的颜色。

这样,你就可以在Flutter应用中显示电池状态了。希望这个示例对你有帮助!

回到顶部