main.dart 2.24 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 10 11
// 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';

class PlatformChannel extends StatefulWidget {
  @override
12
  _PlatformChannelState createState() => _PlatformChannelState();
13 14 15
}

class _PlatformChannelState extends State<PlatformChannel> {
16
  static const MethodChannel methodChannel =
17
      MethodChannel('samples.flutter.io/battery');
18
  static const EventChannel eventChannel =
19
      EventChannel('samples.flutter.io/charging');
20 21 22

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

24
  Future<void> _getBatteryLevel() async {
25 26
    String batteryLevel;
    try {
27 28 29
      final int result = await methodChannel.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level: $result%.';
    } on PlatformException {
30
      batteryLevel = 'Failed to get battery level.';
31
    }
32 33 34 35 36
    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

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

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

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

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

void main() {
83
  runApp(MaterialApp(home: PlatformChannel()));
84
}