Flutter | iOS | 已有项目集成Flutter框架

最近整理开发常用代码时,想用Flutter框架实现iOS和Android两端的UI层页面,正好也好好学习一下Flutter框架的使用

  1. 先执行一下flutter doctor看看开发环境
    我之前的版本是1.12.0,而最新版是1.17.0,控制台会输出相应的更新的命令,更新完了应该是下图的状态

    flutter doctor

  2. 控制台cd到想要保存的项目路径中,执行flutter create --template module 想要起的名称

    创建项目文件

  3. 控制台cd到iOS项目路径中,注意这个路径中要有CocoaPods文件,编辑CocoaPods文件,添加以下几行

flutter_application_path = 'Flutter项目文件夹路径'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'xxx' do
  install_all_flutter_pods(flutter_application_path)
end

添加后我的文件内容长这样


CocoaPod文件内容
  1. 保存文件后执行pod install或者pod update通过Pod安装Flutter类库

    pod update

  2. 使用
    在AppDelegate里实例化FlutterEngine

import UIKit
import Flutter
// Used to connect plugins (only if you have plugins with iOS platform code).
import FlutterPluginRegistrant

@UIApplicationMain
class AppDelegate: FlutterAppDelegate { // More on the FlutterAppDelegate.
  lazy var flutterEngine = FlutterEngine(name: "my flutter engine")

  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Runs the default Dart entrypoint with a default Flutter route.
    flutterEngine.run()
    // Used to connect plugins (only if you have plugins with iOS platform code).
    GeneratedPluginRegistrant.register(with: self.flutterEngine)
    return true
  }
}

在需要展示Flutter页面的地方使用FlutterEngine初始化即可

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("Show 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)
  }
}

至此就可以使用Flutter创建UI应用在iOS和Android两端了

你可能感兴趣的:(Flutter | iOS | 已有项目集成Flutter框架)