flutter和原生项目混合开发 现在Flutter属于试水阶段,要是想在商业app中使用Flutter,目前基本上是将Flutter的页面嵌入到目前先有的iOS或者安卓工程,目前讲混合开发的文章有很多:
不过这些文章大多讲的是安卓和flutter混合开发的,或者单一的iOS和flutter的 试了一下Flutter混合开发,有一些坑,总结给大家
既然用Flutter混合开发,那肯定是希望写一套代码,安卓iOS都能无负担运行,所以在开发的时候,需要满足如下需求:
- Flutter、iOS、安卓工程的目录在同一级,互相之前平级、无嵌套
- 开发iOS的时候,不用操心Flutter部分,只用xcode点击运行就可以(即修改编译iOS项目时,使用编译好的Flutter产物)
- 开发Flutter的时候,不用操心iOS部分,只用android studio点击运行就可以
- 支持模拟器和真机
混合开发最权威的指南当然是flutter自己的wiki
新建目录:
把iOS,安卓项目放进去.然后创建flutter_module
flutter create -t module xxx
目录结构:
flutter:
iOS:
安卓:
_## ==============Flutter ==============_
_## Flutter 模块的路径 pod update --verbose --no-repo-update_
_##绝对路径_
flutter_application_path = '/Users/lishunfeng/Desktop/flutter_ios/Flutter_module'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
_## ==============Flutter ==============_
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
关键代码:
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:**nil** nibName:**nil** bundle:**nil**];
self.window.rootViewController = flutterViewController;
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
"Flutter_module/.android/include_flutter.groovy"
))
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
dependencies {
implementation project(':flutter')
}
1.第一种: 布局:
xml version="1.0" encoding="utf-8"?>
RelativeLayout>
</LinearLayout>
代码:
package com.example.fndroid;
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout;
import io.flutter.facade.Flutter; import io.flutter.view.FlutterView;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout rl = findViewById(R.id.rl_root_view); findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,HomeActivity.class)); } }); View flutterView = Flutter.createView(MainActivity.this, getLifecycle(), "route1"); rl.addView(flutterView);
通过上面的一些讲解,相信就能够使用native+flutter的混合开发了。但细心一点就会发现, 在前面的讲解中,flutter模块并没有与native项目进行通信,那么该如何通信尼?在笔者的下一篇文章会进行详细讲解。