main.dart 2.29 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 31
      batteryLevel = 'Battery level: $result%.';
    } on PlatformException {
32
      batteryLevel = 'Failed to get battery level.';
33
    }
34
    setState(() {
35
      _batteryLevel = batteryLevel;
36 37
    });
  }
38

39 40 41 42 43 44
  @override
  void initState() {
    super.initState();
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  }

45
  void _onEvent(Object? event) {
46 47 48 49 50 51
    setState(() {
      _chargingStatus =
          "Battery status: ${event == 'charging' ? '' : 'dis'}charging.";
    });
  }

52
  void _onError(Object error) {
53
    setState(() {
54
      _chargingStatus = 'Battery status: unknown.';
55 56 57
    });
  }

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

84
void main() {
85
  runApp(const MaterialApp(home: PlatformChannel()));
86
}