Add battery charging status to Platform Channel example (#9147)
diff --git a/examples/platform_channel/lib/main.dart b/examples/platform_channel/lib/main.dart index 6c8c161..19f6738 100644 --- a/examples/platform_channel/lib/main.dart +++ b/examples/platform_channel/lib/main.dart
@@ -1,4 +1,4 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. +// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -13,16 +13,21 @@ } class _PlatformChannelState extends State<PlatformChannel> { - static const PlatformMethodChannel platform = const PlatformMethodChannel('samples.flutter.io/battery'); - String _batteryLevel = ''; + static const PlatformMethodChannel methodChannel = + const PlatformMethodChannel('samples.flutter.io/battery'); + static const PlatformEventChannel eventChannel = + const PlatformEventChannel('samples.flutter.io/charging'); + + String _batteryLevel = 'Battery level: unknown.'; + String _chargingStatus = 'Battery status: unknown.'; Future<Null> _getBatteryLevel() async { String batteryLevel; try { - final int result = await platform.invokeMethod('getBatteryLevel'); - batteryLevel = 'Battery level at $result % .'; - } on PlatformException catch (e) { - batteryLevel = "Failed to get battery level: '${e.message}'."; + final int result = await methodChannel.invokeMethod('getBatteryLevel'); + batteryLevel = 'Battery level: $result%.'; + } on PlatformException { + batteryLevel = "Failed to get battery level."; } setState(() { _batteryLevel = batteryLevel; @@ -30,19 +35,45 @@ } @override + void initState() { + super.initState(); + eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError); + } + + void _onEvent(String event) { + setState(() { + _chargingStatus = + "Battery status: ${event == 'charging' ? '' : 'dis'}charging."; + }); + } + + void _onError(PlatformException error) { + setState(() { + _chargingStatus = "Battery status: unknown."; + }); + } + + @override Widget build(BuildContext context) { return new Material( - child: new Center( - child: new Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: <Widget>[ - new RaisedButton( - child: new Text('Get Battery Level'), - onPressed: _getBatteryLevel, - ), - new Text(_batteryLevel, key: new Key('Battery level label')), - ], - ), + child: new Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: <Widget>[ + new Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[ + new Text(_batteryLevel, key: new Key('Battery level label')), + new Padding( + padding: new EdgeInsets.all(16.0), + child: new RaisedButton( + child: new Text('Refresh'), + onPressed: _getBatteryLevel, + ), + ), + ], + ), + new Text(_chargingStatus), + ], ), ); }