Flutter與原生互動(安卓、iOS),實現原生分享 | 掘金技術徵文

嘟嘟dududu發表於2018-08-10

#這裡主要用到:MethodChannel,做一個簡單的拋磚引玉,下面將分別以安卓和iOS為例子介紹;

需求如下:

  • 1、flutter能夠呼叫原生的控制元件,flutter能夠傳遞引數給原生;
  • 2、原生(安卓、iOS)能夠返回引數給flutter;

下面將介紹具體實現過程:

Flutter與原生互動(安卓、iOS),實現原生分享 | 掘金技術徵文

具體思路:用MethodChannel和原生相關聯,如下程式碼:

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

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

      print("$nativeSay");
複製程式碼

iOS中Appdelegate實現邏輯如下:

Flutter與原生互動(安卓、iOS),實現原生分享 | 掘金技術徵文

就是這麼簡單兩邊建立了聯絡,然後實現分享或者其他功能都OK,這裡以分享舉例;效果如下

Flutter與原生互動(安卓、iOS),實現原生分享 | 掘金技術徵文

右上角新增分享按鈕,程式碼如下:

        actions: <Widget>[
          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<StatefulWidget> createState() {
    // TODO: implement createState
    return new Sharing();
  }
}


class Sharing extends State<ShareAppState> {

  String _talkStrs = "你還看??";

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

  Future<void> 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)
  }
}
複製程式碼

#安卓

Flutter與原生互動(安卓、iOS),實現原生分享 | 掘金技術徵文

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 技術實踐 | 掘金技術徵文,徵文活動正在進行中

相關文章