battery_view.dart 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:flutter/material.dart';
  2. import 'package:device_info/device_info.dart';
  3. import 'dart:io';
  4. import 'package:battery_plus/battery_plus.dart';
  5. import 'package:shuqi/public.dart';
  6. class BatteryView extends StatefulWidget {
  7. @override
  8. _BatteryViewState createState() => _BatteryViewState();
  9. }
  10. class _BatteryViewState extends State<BatteryView> {
  11. double batteryLevel = 0;
  12. @override
  13. void initState() {
  14. super.initState();
  15. getBatteryLevel();
  16. }
  17. getBatteryLevel() async {
  18. DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  19. if (Platform.isAndroid) {
  20. var androidInfo = await deviceInfo.androidInfo;
  21. if (!androidInfo.isPhysicalDevice) {
  22. return;
  23. }
  24. }
  25. if (Platform.isIOS) {
  26. var iosInfo = await deviceInfo.iosInfo;
  27. if (!iosInfo.isPhysicalDevice) {
  28. return;
  29. }
  30. }
  31. var battery = Battery();
  32. var level = await battery.batteryLevel;
  33. battery.onBatteryStateChanged.listen((BatteryState state) {
  34. // Do something with new state
  35. });
  36. setState(() {
  37. this.batteryLevel = level / 100.0;
  38. });
  39. }
  40. @override
  41. Widget build(BuildContext context) {
  42. return Container(
  43. width: 27,
  44. height: 12,
  45. child: Stack(
  46. children: <Widget>[
  47. Image.asset('assets/img/reader_battery.png'),
  48. Container(
  49. margin: EdgeInsets.fromLTRB(2, 2, 2, 2),
  50. width: 20 * batteryLevel,
  51. color: SQColor.golden,
  52. )
  53. ],
  54. ),
  55. );
  56. }
  57. }