main.dart 2.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

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 =
19
      MethodChannel('samples.flutter.io/battery');
20
  static const EventChannel eventChannel =
21
      EventChannel('samples.flutter.io/charging');
22 23 24

  String _batteryLevel = 'Battery level: unknown.';
  String _chargingStatus = 'Battery status: unknown.';
25

26
  Future<void> _getBatteryLevel() async {
27
    String batteryLevel;
28
    try {
29
      final int? result = await methodChannel.invokeMethod('getBatteryLevel');
30
      batteryLevel = 'Battery level: $result%.';
31 32 33 34 35 36
    } on PlatformException catch (e) {
      if (e.code == 'NO_BATTERY') {
        batteryLevel = 'No battery.';
      } else {
        batteryLevel = 'Failed to get battery level.';
      }
37
    }
38
    setState(() {
39
      _batteryLevel = batteryLevel;
40 41
    });
  }
42

43 44 45 46 47 48
  @override
  void initState() {
    super.initState();
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  }

49
  void _onEvent(Object? event) {
50 51 52 53 54 55
    setState(() {
      _chargingStatus =
          "Battery status: ${event == 'charging' ? '' : 'dis'}charging.";
    });
  }

56
  void _onError(Object error) {
57
    setState(() {
58
      _chargingStatus = 'Battery status: unknown.';
59 60 61
    });
  }

62 63
  @override
  Widget build(BuildContext context) {
64 65
    return Material(
      child: Column(
66 67
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
68
          Column(
69 70
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
71 72
              Text(_batteryLevel, key: const Key('Battery level label')),
              Padding(
73
                padding: const EdgeInsets.all(16.0),
74
                child: ElevatedButton(
75
                  onPressed: _getBatteryLevel,
76
                  child: const Text('Refresh'),
77 78 79 80
                ),
              ),
            ],
          ),
81
          Text(_chargingStatus),
82
        ],
83
      ),
84 85 86
    );
  }
}
87

88
void main() {
89
  runApp(const MaterialApp(home: PlatformChannel()));
90
}