| 1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | import 'dart:async'; |
| 6 | |
| 7 | import 'package:flutter/material.dart'; |
| 8 | import 'package:flutter/services.dart'; |
| 9 | |
| 10 | class PlatformChannel extends StatefulWidget { |
| 11 | const PlatformChannel({super.key}); |
| 12 | |
| 13 | @override |
| 14 | State<PlatformChannel> createState() => _PlatformChannelState(); |
| 15 | } |
| 16 | |
| 17 | class _PlatformChannelState extends State<PlatformChannel> { |
| 18 | static const MethodChannel methodChannel = MethodChannel('samples.flutter.io/battery' ); |
| 19 | static const EventChannel eventChannel = EventChannel('samples.flutter.io/charging' ); |
| 20 | |
| 21 | String _batteryLevel = 'Battery level: unknown.' ; |
| 22 | String _chargingStatus = 'Battery status: unknown.' ; |
| 23 | |
| 24 | Future<void> _getBatteryLevel() async { |
| 25 | String batteryLevel; |
| 26 | try { |
| 27 | final int? result = await methodChannel.invokeMethod('getBatteryLevel' ); |
| 28 | batteryLevel = 'Battery level: $result%.' ; |
| 29 | } on PlatformException catch (e) { |
| 30 | if (e.code == 'NO_BATTERY' ) { |
| 31 | batteryLevel = 'No battery.' ; |
| 32 | } else { |
| 33 | batteryLevel = 'Failed to get battery level.' ; |
| 34 | } |
| 35 | } |
| 36 | setState(() { |
| 37 | _batteryLevel = batteryLevel; |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | @override |
| 42 | void initState() { |
| 43 | super.initState(); |
| 44 | eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError); |
| 45 | } |
| 46 | |
| 47 | void _onEvent(Object? event) { |
| 48 | setState(() { |
| 49 | _chargingStatus = "Battery status: ${event == 'charging' ? '' : 'dis' }charging." ; |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | void _onError(Object error) { |
| 54 | setState(() { |
| 55 | _chargingStatus = 'Battery status: unknown.' ; |
| 56 | }); |
| 57 | } |
| 58 | |
| 59 | @override |
| 60 | Widget build(BuildContext context) { |
| 61 | return Material( |
| 62 | child: Column( |
| 63 | mainAxisAlignment: MainAxisAlignment.spaceEvenly, |
| 64 | children: <Widget>[ |
| 65 | Column( |
| 66 | mainAxisAlignment: MainAxisAlignment.center, |
| 67 | children: <Widget>[ |
| 68 | Text(_batteryLevel, key: const Key('Battery level label' )), |
| 69 | Padding( |
| 70 | padding: const EdgeInsets.all(16.0), |
| 71 | child: ElevatedButton(onPressed: _getBatteryLevel, child: const Text('Refresh' )), |
| 72 | ), |
| 73 | ], |
| 74 | ), |
| 75 | Text(_chargingStatus), |
| 76 | ], |
| 77 | ), |
| 78 | ); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | void main() { |
| 83 | runApp(const MaterialApp(home: PlatformChannel())); |
| 84 | } |
| 85 | |