最近整理開發(fā)常用代碼時集绰,想用Flutter框架實現(xiàn)iOS和Android兩端的UI層頁面,正好也好好學習一下Flutter框架的使用
-
先執(zhí)行一下
flutter doctor
看看開發(fā)環(huán)境
我之前的版本是1.12.0八拱,而最新版是1.17.0,控制臺會輸出相應的更新的命令呀酸,更新完了應該是下圖的狀態(tài)
-
控制臺cd到想要保存的項目路徑中厅篓,執(zhí)行
flutter create --template module 想要起的名稱
控制臺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
添加后我的文件內(nèi)容長這樣
-
保存文件后執(zhí)行
pod install
或者pod update
通過Pod安裝Flutter類庫
使用
在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創(chuàng)建UI應用在iOS和Android兩端了