Flutter TipsFlutter

/ / 2015-10-25
Flutter平台特性 : Android:Flutter dart和java调用 消息和响应是异步传递的,以确保用户界面保持响应(不会挂起)。 Future void _getBatteryLevel () async { String batterylevel ; try { final int result = await methodChannel .invokeMethod( getBatte...

Flutter平台特性 :
Android:Flutter dart和java调用

消息和响应是异步传递的,以确保用户界面保持响应(不会挂起)。

Future<void> _getBatteryLevel() async{
  String batterylevel;
  try{
    final int result  = await methodChannel.invokeMethod('getBatteryLevel');
    batterylevel = 'battery level: $result %.';
  }catch(exception){
    batterylevel = "battery error:!!.";
  }

  setState(() {
    _batteryLevel = batterylevel;
  });
}
Future 和async的用法

java中实现具体的方法:
new MethodChannel(getFlutterView(),BATTERY_CHANNEL).setMethodCallHandler(
        new MethodChannel.MethodCallHandler() {
          @java.lang.Override
          public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
            if(methodCall.method.equals("getBatteryLevel")){
              int batterlevel = getBatterLevel();

              if(batterlevel != -1)
              {
                result.success(batterlevel);
              }
              else{
                result.error("get failed","battery level not available",null);
              }
            }else{
              result.notImplemented();
            }
          }
        }

);

反过来也可以从java或者oc调用到flutter dart,使用eventchannel
java:
new EventChannel(getFlutterView(),CHARGING_CHANNEL).setStreamHandler(
        new StreamHandler() {
          private BroadcastReceiver chargingStateChangeReceiver;
          @Override
          public void onListen(Object o, EventSink eventSink) {
            chargingStateChangeReceiver = CreateChargingBroadcastReceiever(eventSink);
            registerReceiver(chargingStateChangeReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
          }

          @Override
          public void onCancel(Object o) {

          }
        }
);

dart:

String _chargingStatus = 'Charging Battery status: unknown.';
eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
void _onError(Object error) {
  setState(() {
    _chargingStatus = 'Battery status: unknown.';
  });
}

void _onEvent(Object event) {
  setState(() {
    _chargingStatus =
    "Battery status: ${event == 'charging' ? '' : 'dis'}charging.";
  });
}



1