Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生
创建 Flutter module
cd ios 项目根目录
flutter create --template module my_flutter
将Flutter模块嵌入到现有应用程序中
- 使用CocoaPods和已安装的Flutter SDK(推荐)。
- 为Flutter引擎,已编译的Dart代码和所有Flutter插件创建 frameworks。手动嵌入 frameworks,并在Xcode中更新现有应用程序的构建设置。
使用CocoaPods和已安装的Flutter SDK
flutter_application_path = '../my_flutter'
load File.join(flutter_application_path,'.ios','Flutter','podhelper.rb')
target 'My App' do
install_all_flutter_pods(flutter_application_path)
end
在Xcode中嵌入 Flutter Frameworks
flutter build ios-framework --output=./Flutter/
创建 FlutterEngine 和 FlutterViewController
import UIKit
import Flutter
@UIApplicationMain
class AppDelegate: FlutterAppDelegate {
lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
flutterEngine.run();
return super.application(application,didFinishLaunchingWithOptions: launchOptions);
}
}
import UIKit
import Flutter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type:UIButton.ButtonType.custom)
button.addTarget(self,action: #selector(showFlutter),for: .touchUpInside)
button.setTitle("显示 Flutter",for: UIControl.State.normal)
button.frame = CGRect(x: 80.0,y: 210.0,width: 160.0,height: 40.0)
button.backgroundColor = UIColor.blue
self.view.addSubview(button)
}
@objc func showFlutter() {
let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterViewController =
FlutterViewController(engine: flutterEngine,nibName: nil,bundle: nil)
present(flutterViewController,animated: true,completion: nil)
}
}
func showFlutter() {
let flutterViewController = FlutterViewController(project: nil,bundle: nil)
present(flutterViewController,completion: nil)
}
指定入口点
flutterEngine.run(withEntrypoint: "newEntrypoint",libraryURI: "main.dart")
初始化路由
let flutterEngine = FlutterEngine()
flutterEngine.run(
withEntrypoint: FlutterDefaultDartEntrypoint,initialRoute: "/one_page")