Flutter与原生交互(安卓、iOS),实现原生分享 | 掘金技术征文

#这里主要用到:MethodChannel,做一个简单的抛砖引玉,下面将分别以安卓和iOS为例子介绍;

需求如下:

  • 1、flutter能够调用原生的控件,flutter能够传递参数给原生;
  • 2、原生(安卓、iOS)能够返回参数给flutter;

下面将介绍具体实现过程:

具体思路:用MethodChannel和原生相关联,如下代码:

      final channel = const MethodChannel('channel:Chenli');

      final String nativeSay = await channel.invokeMethod('ChenliShareFile', '你好native,我是flutter,提前祝七夕快乐');

      print("$nativeSay");
复制代码

iOS中Appdelegate实现逻辑如下:

就是这么简单两边建立了联系,然后实现分享或者其他功能都OK,这里以分享举例;效果如下

右上角添加分享按钮,代码如下:

        actions: [
          IconButton(
              icon: Icon(Icons.share),
              onPressed: testShare)
        ],
复制代码

整体代码如下: #flutter:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';

class shareApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: "Share",
      home: ShareAppState(),
    );
  }
}

class ShareAppState extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return new Sharing();
  }
}


class Sharing extends State {

  String _talkStrs = "你还看??";

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('Share'),
        actions: [
          IconButton(
              icon: Icon(Icons.share),
              onPressed: testShare)
        ],
      ),
      body: new Center(
          child: Text(_talkStrs),
      ),
      
    );
  }

  Future testShare() async {
    String talkStrs;
    try {
      final channel = const MethodChannel('channel:Chenli');

      final String nativeSay = await channel.invokeMethod('ChenliShareFile', '你好native,我是flutter,提前祝七夕快乐');

      print("$nativeSay");

      setState(() {
        _talkStrs = nativeSay;
      });

    } catch(e) {
      print(e.toString());
    }

  }

}
复制代码

#iOS:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    let controller:FlutterViewController = self.window.rootViewController as! FlutterViewController
    let shareChannel = FlutterMethodChannel.init(name: "channel:Chenli", binaryMessenger: controller)
    shareChannel .setMethodCallHandler { (call, result) in
        if ("ChenliShareFile" == call.method) {
            //这里调用
            print("这里使用flutter里面传递的参数:%@",call.arguments);
            let alert = UIActivityViewController.init(activityItems: [call.arguments ?? "哈哈哈"], applicationActivities: nil)
            controller .present(alert, animated: true, completion: nil)
            //这里iOS传递参数给flutter
            result("??,flutter七夕还是单身吗?")
        }
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
复制代码

#安卓

package chenli.flutterjoke

import android.content.Intent
import android.os.Bundle

import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity(): FlutterActivity() {

  private val SHARE_CHANNEL = "channel:Chenli"

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    MethodChannel(this.flutterView, SHARE_CHANNEL).setMethodCallHandler { methodCall, result ->
      if (methodCall.method == "ChenliShareFile") {
//        print(methodCall.arguments)
        shareFile(methodCall.arguments as String)
      }
    }
  }

  private fun shareFile(path: String) {
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.type = "text/plain"
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "每日一笑")//添加分享内容标题
    shareIntent.putExtra(Intent.EXTRA_TEXT,path)//添加分享内容
    this.startActivity(Intent.createChooser(shareIntent, "分享"))
  }
}

复制代码

从 0 到 1:我的 Flutter 技术实践 | 掘金技术征文,征文活动正在进行中

你可能感兴趣的:(Flutter与原生交互(安卓、iOS),实现原生分享 | 掘金技术征文)