注册

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

Xcode:Version 11.3.1 (11C504)
Swift:5.0
iOS项目地址
Flutter项目创建

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

文件路径如下:

753e0f1d04c76ca5ccd0c43cff6698cb.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统治全世界。

转自:https://www.jianshu.com/p/351bd8ecbc79

0 个评论

要回复文章请先登录注册