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


