在上一篇文章Flutter(六):Flutter_Boost接入現有原生工程(iOS+Android)中介紹了Flutter_Boost的接入方法,這一篇將介紹Flutter自帶的接入方法。 新建工程 1.新建工程 1.使用Xcode新建flutter_demo_ios(模擬已有工程) 2.使用An ...
在上一篇文章Flutter(六):Flutter_Boost接入現有原生工程(iOS+Android)中介紹了Flutter_Boost的接入方法,這一篇將介紹Flutter自帶的接入方法。
新建工程
1.新建工程
- 1.使用Xcode新建flutter_demo_ios(模擬已有工程)
- 2.使用AndroidStudio新建flutter_demo_android(模擬已有工程)
- 3.使用AndroidStudio新建flutter_demo_flutter(新的flutter庫工程)
備註:
1.AndroidSudio需要安裝Dart和Flutter插件
2.flutter工程新建時選擇Module
2.新建完成
目錄結構如下:
Android接入
1.setting.gradle新增
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
'flutter_demo_library/.android/include_flutter.groovy'
))
2.app下的build.gradle增加依賴
implementation project(':flutter')
然後執行gradle sync
3.跳轉代碼
startActivity(FlutterActivity.createDefaultIntent(currentActivity))
iOS接入
1.修改pod文件
flutter_application_path = '../flutter_demo_library'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'flutter_demo_ios' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for flutter_demo_ios
install_all_flutter_pods(flutter_application_path)
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
end
執行pod install
,podhelper.rb 腳本會把你的 plugins, Flutter.framework,和 App.framework 集成到你的項目中。
2.修改ViewController中的跳轉代碼
let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
self.navigationController?.pushViewController(flutterViewController, animated: true)
ViewController記得還需要import Flutter
,至此iOS接入完畢,使用模擬器也可以正常執行。
問題集錦
Android
1、Caused by: org.gradle.api.InvalidUserCodeException: Build was configured to prefer settings repositories over project repositories but repository 'maven' was added by plugin class 'FlutterPlugin'
原因:Android項目和Flutter項目的Gradle配置不一樣
解決方案:
1、只是demo的話,把Flutter/.android/根目錄下的setting.gradle和build.gradl拷貝到Android/根目錄下,替換Android項目自帶的
2、如果是老的工程,可以參考Flutter 混合開發組件化與工程化架構
2.解決Flutter 交互頁面可見之前會有一個短暫的延遲
原因:每一個 FlutterActivity 預設會創建它自己的 FlutterEngine。每一個 FlutterEngine 會有一個明顯的預熱時間。這意味著載入一個標準的 FlutterActivity 時,在你的 Flutter 交互頁面可見之前會有一個短暫的延遲。
解決方案:想要最小化這個延遲時間,你可以在抵達你的 FlutterActivity 之前,初始化一個 FlutterEngine,然後使用這個已經預熱好的 FlutterEngine。
在Application加入代碼:
class MyApplication : Application() {
lateinit var flutterEngine : FlutterEngine
override fun onCreate() {
super.onCreate()
// Instantiate a FlutterEngine.
flutterEngine = FlutterEngine(this)
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
// Cache the FlutterEngine to be used by FlutterActivity.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine)
}
}
跳轉代碼:
startActivity(FlutterActivity
.withCachedEngine("my_engine_id")
.build(this))