在 Android 中集成 Flutter 的学习笔记,flutter 登录跳转
flutter create -t module my_flutter
来创建一个 flutter 的 module,成功之后,目录结构如下:
接着我们来修改一下 Android 功能里的 gradle 文件:
首先是 app 的 setting.gradle 文件,添加如下:
include ':app'setBinding(new Binding([gradle: this]))evaluate(new File(settingsDir.parentFile,'my_flutter/.android/include_flutter.groovy'))
目的就是去加载指定目录的 include_flutter.groovy 文件,那么我们查看一下这个文件:
// Generated file. Do not edit.def scriptFile = getClass().protectionDomain.codeSource.location.pathdef flutterProjectRoot = new File(scriptFile).parentFile.parentFilegradle.include ':flutter'gradle.project(':flutter').projectDir = new File(flutterProjectRoot, '.android/Flutter')def plugins = new Properties()def pluginsFile = new File(flutterProjectRoot, '.flutter-plugins')if (pluginsFile.exists()) {pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }}plugins.each { name, path ->def pluginDirectory = flutterProjectRoot.toPath().resolve(path).resolve('android').toFile()gradle.include ":name").projectDir = pluginDirectory}gradle.getGradle().projectsLoaded { g ->g.root
Project.afterEvaluate { p ->p.subprojects { sp ->if (sp.name != 'flutter') {sp.evaluationDependsOn(':flutter')}}}}
其中最重要的一段代码,就是 include ':flutter',意思就是 flutter 这个 module 要参与编译。
接着在 app 层级(不是 project 层)的 build.gradle 文件中添加依赖:
dependencies {implementation project(':flutter'):}
OK 配置阶段结束,我们开始先写 Android 代码,在 activity 中添加一个 button,当我们点击它时,将加载 flutter 布局,代码如下:
public class MainActivity extends AppCompatActivity {private TextView button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {FragmentTransaction tx = getSupportFragmentManager().beginTransaction();tx.replace(R.id.container, Flutter.createFragment("route1"));tx.commit();// View flutterView = Flutter.createView(MainActivity.this,getLifecycle(),"route1");// FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(100,100);// params.leftMargin = 100;// params.topMargin = 200;// addContentView(flutterView,params);}});}}
这里有两种实现方式,一种是使用 fragment,一种是使用 FlutterView。代码中的 route1 字符串则是 flutter 代码中定义的,接下来就开始写 flutter 代码:
评论