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<StatefulWidget> createState() {
    return new HomeAppState();
  }
}

class HomeAppState extends State<HomeApp> {

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

  Future<Null> _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: <Widget>[
        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;
  }
}

运行:点击按钮

这里写图片描述

已标记关键词 清除标记
<p>本套课程适用于有一定的<span style="color: #e03e2d;">iOS、Android、Flutter</span>开发基础。</p> <p>学完本次课程,能够让大家对Flutter如何调用移动端原生页面有一个清晰的认识;在纯Flutter开发过程中遇到需要调用原生功能的时候,能够快速定制属于自己或者公司的私有插件- Plugin。</p> <p>课程一共氛围两部分:</p> <p>1、Flutter插件跟iOS的交互部分:包括调用iOS原生页面、如何使用iOS的<span style="color: #e03e2d;">framework二进制</span>、<span style="color: #e03e2d;">bundle资源文件</span>、依赖的cocoapods资源;</p> <p>2、Flutter插件跟安卓的交互部分:包括调用Android原生页面、如何接收原生页面的回调、如何使用aar文件、依赖的其他资源。</p> <p>最终能够帮助大家定制私有插件;提升工作技能。</p> <p><span style="color: #e03e2d;">备注:课程中使用环境</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #2fb41d;">[✓]</span><span style="font-variant-ligatures: no-common-ligatures;"> Flutter (Channel stable, 1.22.5, on macOS 11.0.1 20B29 darwin-arm, locale zh-Hans-CN)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9); min-height: 14px;"><span style="font-variant-ligatures: no-common-ligatures;"> </span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #9fa01c;">[!]</span><span style="font-variant-ligatures: no-common-ligatures;"> Android toolchain - develop for Android devices (Android SDK version 30.0.3)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #00ff00; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures;">    </span><span style="font-variant-ligatures: no-common-ligatures; color: #9fa01c;">!</span><span style="font-variant-ligatures: no-common-ligatures;"> Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #2fb41d;">[✓]</span><span style="font-variant-ligatures: no-common-ligatures;"> Xcode - develop for iOS and macOS (Xcode 12.2)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #9fa01c;">[!]</span><span style="font-variant-ligatures: no-common-ligatures;"> Android Studio (version 4.1)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #2fb41d;">[✓]</span><span style="font-variant-ligatures: no-common-ligatures;"> IntelliJ IDEA Community Edition (version 2020.3)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"><span style="font-variant-ligatures: no-common-ligatures; color: #2fb41d;">[✓]</span><span style="font-variant-ligatures: no-common-ligatures;"> Connected device (1 available)</span></p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9); min-height: 14px;"> </p> <p style="margin: 0px; font-stretch: normal; font-size: 12px; line-height: normal; font-family: 'Andale Mono'; color: #2fff12; background-color: rgba(0, 0, 0, 0.9);"> </p>
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页