Flutter集成到Swift老项目 使用pod接入flutter

Xcode:Version 11.3.1 (11C504)
Swift:5.0

iOS项目地址

Flutter项目创建

cd some/path/
flutter create --template module flutter_yyframework

文件路径如下:


image.png

cd 到你要混编的项目(YYFramework)同一个路径下 ,执行如下:

flutter create -t module flutter_yyframework

Podfile 文件

#注意路径和文件夹名字正确无误 最后有一个反斜杠
flutter_application_path = '/Users/houjianan/Documents/GitHub/iOS/flutter_yyframework/'
load File.join(flutter_application_path, 'YYFramework', 'Flutter', 'podhelper.rb')

  target 'YYFramework' do
  install_all_flutter_pods(flutter_application_path)
  
end

注:YYFramework 是iOS项目的文件名
添加好之后

pod install

注意,如下错误:[!] InvalidPodfilefile: No such file or directory @ rb_sysopen - ./flutter_yyframework/.ios/Flutter/podhelper.rb.

需要在flutter_yyframework文件夹下执行以下命令,把.ios和.android等flutter配置生成出来。(打开模拟器。链接真机都可以。)

open -a Simulator
flutter run

注意,如下错误是因为路径不对。

[!] Invalid `Podfile` file: cannot load such file -- path/to/flutter_yyframework/.ios/Flutter/podhelper.rb.

 #  from /Users/houjianan/Documents/GitHub/iOS/YYFramework/Podfile:7
 #  -------------------------------------------
 #  flutter_application_path = 'path/to/flutter_yyframework/'
 >  load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
 #  
 #  -------------------------------------------
houjianan:YYFramework> pod install
Analyzing dependencies
Downloading dependencies
Installing Flutter (1.0.0)
Installing FlutterPluginRegistrant (0.0.1)
Installing flutter_yyframework (0.0.1)
Generating Pods project
Integrating client project
Pod installation complete! There are 42 dependencies from the Podfile and 51 total pods installed.
houjianan:YYFramework> 


iOS Swift代码

//
//  AppDelegate.swift
//  YYFramework
//
//  Created by houjianan on 2018/8/11.
//  Copyright © 2018年 houjianan. All rights reserved.
//

import UIKit
import SwiftTheme
import PLShortVideoKit
import Flutter
import FlutterPluginRegistrant // Used to connect plugins.

@UIApplicationMain
// 集成FlutterAppDelegate之后代理方法要override
class AppDelegate: FlutterAppDelegate {

    lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
    
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print(NSHomeDirectory())
        flutter_run()
        return true
    }
    
}

//
//  AppDelegate+Flutter.swift
//  YYFramework
//
//  Created by houjianan on 2020/1/20.
//  Copyright © 2020 houjianan. All rights reserved.
//

import Foundation
import Flutter
import FlutterPluginRegistrant // Used to connect plugins.

extension AppDelegate {
    
    func flutter_run() {
        flutterEngine.run()
        GeneratedPluginRegistrant.register(with: self.flutterEngine)
    }
}

//
//  GAFlutterRooterViewController.swift
//  YYFramework
//
//  Created by houjianan on 2020/1/20.
//  Copyright © 2020 houjianan. All rights reserved.
//

import UIKit
import Flutter

class GAFlutterRooterViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    @IBAction func bAction(_ sender: Any) {
        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
        let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        present(flutterViewController, animated: true, completion: nil)
    }
    
    @IBAction func cAction(_ sender: Any) {
        let flutterViewController = FlutterViewController(project: nil, nibName: nil, bundle: nil)
        
        flutterViewController.setInitialRoute("MyApp")
        
        let channel = FlutterMethodChannel(name: "com.pages.your/native_get", binaryMessenger: flutterViewController as! FlutterBinaryMessenger)
        channel.setMethodCallHandler { (call, result) in
            print("method = ", call.method, "arguments = ", call.arguments ?? "argumentsNULL", result)
            
            let method = call.method
            if method == "FlutterPopIOS" {
                print("FlutterPopIOS:返回来传的参数是 == ", call.arguments ?? "argumentsNULL")
                self.navigationController?.popViewController(animated: true)
            } else if method == "FlutterCickedActionPushIOSNewVC" {
                print("FlutterCickedActionPushIOSNewVC:返回来传的参数是 == ", call.arguments ?? "argumentsNULL")
                let vc = GAVerificationCodeViewController(nibName: "GAVerificationCodeViewController", bundle: nil)
                self.navigationController?.pushViewController(vc, animated: true)
            } else if method == "FlutterGetIOSArguments" {
                let dic = ["a":"value"]
                print("传参给Flutter:", dic)
                result(dic)
            } else {
                
            }
            
        }
        self.navigationController?.pushViewController(flutterViewController, animated: true)
    }
}

Flutter代码

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BotToastInit(
      child:  MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        navigatorObservers: [BotToastNavigatorObserver()],
        home: MyHomePage(title: '1235777'),
      ),
    );
  }
}


class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String _textString = "00";

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  // 创建一个给native的channel (类似iOS的通知)
  static const MethodChannel methodChannel = MethodChannel('com.pages.your/native_get');

  _iOSPushToVC() async {
    await methodChannel.invokeMethod('FlutterPopIOS', '参数');
  }

  void _backAction() {
    _iOSPushToVC();
  }

  void _pushIOSNewVC() async {
    Map<String, dynamic> map = {"code": "200", "data":[1,2,3]};

    await methodChannel.invokeMethod('FlutterCickedActionPushIOSNewVC', map);
  }

  Future<void> _FlutterGetIOSArguments(para) async {
    BotToast.showText(text:"_FlutterGetIOSArguments");
    try {
      final result = await methodChannel.invokeMethod('FlutterGetIOSArguments', para);


      BotToast.showText(text:result["a"]);
      _textString = result["a"];
    } on PlatformException catch (error) {
      print(error);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times1:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            FloatingActionButton(
              onPressed: _backAction,
              child: Icon(Icons.accessibility),
            ),
            FloatingActionButton(
              onPressed: _pushIOSNewVC,
              child: Icon(Icons.accessibility),
            ),
            FloatingActionButton(
              onPressed:() {
                _FlutterGetIOSArguments("flutter传值");
                // 刷新界面
                setState(() {});
            },
              child: Icon(Icons.accessibility),
            ),
            Text(_textString),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}


官网Integrate a Flutter module into your iOS project
很久之前写的一篇《Flutter和原生iOS交互》

过年了,有点时间玩Flutter!
Flutter统治全世界。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,126评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,254评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,445评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,185评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,178评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,970评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,276评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,927评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,400评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,883评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,997评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,646评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,213评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,204评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,423评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,423评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,722评论 2 345

推荐阅读更多精彩内容