移動裝置上最重要的資訊之一就是電池電量了,所以就來讀取一下電池電量吧!!
可以讀取有關運行應用程式的裝置的電池的各種資訊。
// Import package
import 'package:battery_plus/battery_plus.dart';
// Instantiate it
var battery = Battery();
// Access current battery level
print(await battery.batteryLevel);
// Be informed when the state (full, charging, discharging) changes
battery.onBatteryStateChanged.listen((BatteryState state) {
// Do something with new state
});
直接在 pubspec.yaml 加上 battery_plus: ^4.0.2,然後pub get
dependencies:
battery_plus: ^4.0.2
在 /lib/main.dart 加入 程式
import 'package:battery_plus/battery_plus.dart';
宣告和初始化
class _MyHomePageState extends State<MyHomePage> {
final Battery _battery = Battery();
BatteryState? _batteryState;
...
void initState() {
_battery.batteryState.then(_updateBatteryState);
_batteryStateSubscription =
_battery.onBatteryStateChanged.listen(_updateBatteryState);
}
void _updateBatteryState(BatteryState state) {
if (_batteryState == state) return;
setState(() {
_batteryState = state;
});
}
//讀取電量
Text(
'$_batteryState',
style: const TextStyle(fontSize: 24),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () {
_battery.batteryLevel.then(
(batteryLevel) {
showDialog<void>(
context: context,
builder: (_) => AlertDialog(
content: Text('鐵人賽電量 : $batteryLevel%'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('完賽'),
)
],
),
);
},
);
},
child: const Text('Day22 鐵人賽電量'),
),
//讀取是否為省電模式
ElevatedButton(
onPressed: () {
_battery.isInBatterySaveMode.then(
(isInPowerSaveMode) {
showDialog<void>(
context: context,
builder: (_) => AlertDialog(
title: const Text(
'是鐵人賽省電模式嗎?',
style: TextStyle(fontSize: 20),
),
content: Text(
(isInPowerSaveMode == true)? '是' : '否',
style: const TextStyle(fontSize: 18),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('完賽去'),
)
],
),
);
},
);
},
child: const Text('是鐵人賽省電模式嗎?'),
)
讀取電量
是否為省電模式
是不是簡單又方便,就可以讀取電池的電量和狀態呀!