Flutter | iOS | 已有項(xiàng)目集成Flutter框架

最近整理開發(fā)常用代碼時(shí),想用Flutter框架實(shí)現(xiàn)iOS和Android兩端的UI層頁面,正好也好好學(xué)習(xí)一下Flutter框架的使用

  1. 先執(zhí)行一下flutter doctor看看開發(fā)環(huán)境
    我之前的版本是1.12.0,而最新版是1.17.0,控制臺會(huì)輸出相應(yīng)的更新的命令,更新完了應(yīng)該是下圖的狀態(tài)

    flutter doctor

  2. 控制臺cd到想要保存的項(xiàng)目路徑中,執(zhí)行flutter create --template module 想要起的名稱

    創(chuàng)建項(xiàng)目文件

  3. 控制臺cd到iOS項(xiàng)目路徑中,注意這個(gè)路徑中要有CocoaPods文件,編輯CocoaPods文件,添加以下幾行

flutter_application_path = 'Flutter項(xiàng)目文件夾路徑'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'xxx' do
  install_all_flutter_pods(flutter_application_path)
end

添加后我的文件內(nèi)容長這樣


CocoaPod文件內(nèi)容
  1. 保存文件后執(zhí)行pod install或者pod update通過Pod安裝Flutter類庫

    pod update

  2. 使用
    在AppDelegate里實(shí)例化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創(chuàng)建UI應(yīng)用在iOS和Android兩端了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容