Flutter的菜鸟教程二十四:Flutter和原生平台交互

本文将学习和原生平台交互,我们通过一个小案例来演示和Android平台的交互,ios? 你让我用window10演示ios?


MethodChannel:
用于使用异步方法调用与平台插件通信的通道
“samples.flutter.io/battery” 为通道标识,名称相同的通道会干扰彼此的通信
其他的注释应该说的清楚了

import 'dart:async';

/**
 *使用平台通道调用原生代码
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    title: "input",
    home: new Scaffold(
      appBar: new AppBar(
        title: new Text("输入事件"),
      ),
      body: new HomeApp(),
    ),
  ));
}

class HomeApp extends StatefulWidget {
  @override
  State createState() {
    return new HomeAppState();
  }
}

class HomeAppState extends State<HomeApp> {

  static const platform = const MethodChannel("samples.flutter.io/battery");
  String _batteryLevel = "Unknown battery level.";

  Future _getBatteryLevel() async {
    String batteryLevel;
    try {
      print("dart -_getBatteryLevel");
//      在通道上调用此方法
      final int result = await platform.invokeMethod("getBatteryLevel");
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }
    setState(() {
      print("dart -setState");
      _batteryLevel = batteryLevel;
    });
  }

  @override
  Widget build(BuildContext context) {
    print("dart -build");
    return new Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        new RaisedButton(
          onPressed: _getBatteryLevel,
          child: new Text("Get battery level"),
        ),
        new Text("当前电量:$_batteryLevel"),
      ],
    );
  }
}

下面是MainActivity代码

package chen.myweather;


import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
  private static final String CHANNEL = "samples.flutter.io/battery";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//    setMethodCallHandler在此通道上接收方法调用的回调
    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
              @Override
              public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
//                通过methodCall可以获取参数和方法名  执行对应的平台业务逻辑即可
                if (methodCall.method.equals("getBatteryLevel")) {
                  int batteryLevel = getBatteryLevel();
                  if (batteryLevel != -1) {
                    result.success(batteryLevel);
                  } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null);
                  }
                } else {
                  result.notImplemented();
                }
              }
            }
    );
  }

  /**
   * 获取电池电量
   *
   * @return
   */
  private int getBatteryLevel() {

    int batteryLevel = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
      batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    } else {
      Intent intent = new ContextWrapper(getApplicationContext()).
              registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
              intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    }
    return batteryLevel;
  }
}

运行:点击按钮

Flutter的菜鸟教程二十四:Flutter和原生平台交互_第1张图片

你可能感兴趣的:(Flutter,Flutter的菜鸟教程)