Flutter学习笔记之-原生项目集成Flutter模块
原生项目集成Flutter模块适合用于以下场景:
1、重写整个项目存在很大成本的时候
2、只想某一个功能模块采用Flutter试水项目的时候
原生项目集成Flutter模块步骤
- 创建Flutter模块项目
1、创建Flutter模块项目
flutter create --template module mudule_demo
2、编写Flutter模块的代码
- iOS原生项目集成Flutter
采用CocoaPods来管理Flutter依赖。将iOS原生项目和mudule_demo放在同一级目录(也可以不放在同一个目录,根据自己的安排处理)。
1、编写Podfile文件
flutter_application_path = '../mudule_demo'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'iOSDemo' do
use_frameworks!
install_all_flutter_pods(flutter_application_path)
end
2、利用pod install安装依赖
3、编写原生代码跳转flutter module页面
import Flutter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func jumpFlutterModule(_ sender: UIButton) {
// 单开flutter模块的页面
let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterViewController =
FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
present(flutterViewController, animated: true, completion: nil)
// 方式二: 隐试创建FlutterViewController
// let flutterViewController = FlutterViewController(project: nil, nibName: nil, bundle: nil)
// present(flutterViewController, animated: true, completion: nil)
}
}
demo效果:
- Android中集成Flutter模块
1、在settings.gradle中配置如下
// 添加如下代码,注意目录结构路径
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
'mudule_demo/.android/include_flutter.groovy'
))
2、在build.gradle中添加flutter依赖
implementation project(':flutter')
3、在AndroidManifest.xml中注册FlutterActivity配置
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/AppTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
/>
4、添加原生代码跳转到flutter模块
Button jump = findViewById(R.id.jump_flutter);
jump.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(FlutterActivity.createDefaultIntent(MainActivity.this));
}
});
遇到的错误:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androiddemo/com.example.androiddemo.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.androiddemo.MainActivity"
解决办法:
在build中配置
android {
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
}
调试
在原生项目中如何启用Flutter中的热加载技术呢?
flutter attach -d 16E98A9A-DDA2-4EDF-8235-1C14029CE955 --app-id com.30san.wjt.iOSDemo