引入源码前的配置:
新建安卓原生项目FlutterNativeApp,
执行命令
cd FlutterNativeApp/
flutter create -t module my_flutter
在尝试将Flutter模块项目连接到主机Android应用程序之前,请确保您的主机Android应用程序在应用程序的build.gradle文件中声明以下源兼容性:
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
将Flutter模块作为子项目包含在Host应用程序的settings.gradle中:
include ':app'
setBinding(new Binding([gradle: this]))
evaluate(new File('my_flutter/.android/include_flutter.groovy'))
//原文是这样的,但是无法正确编译,去掉settingsDir.parentFile之后就行了
//evaluate(new File(settingsDir.parentFile, 'my_flutter/.android/include_flutter.groovy' ))
引入Flutter模块:
implementation project(':flutter’)
使用Flutter模块的Java API将Flutter视图添加到主应用程序。这可以通过直接使用Flutter.createView来完成
View flutterView = Flutter.createView(
MainActivity.this,
getLifecycle(),
"route1"
);
setContentView(flutterView);
也可以创建一个FlutterFragment来自己处理生命周期:
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.someContainer, Flutter.createFragment("route1"));
tx.commit();
上面我们使用字符串“route1”来告诉Dart代码在Flutter视图中显示哪个小部件。Flutter模块项目模板的lib / main.dart文件应该打开提供的路径字符串(可用作window.defaultRouteName),以确定要创建哪个窗口小部件并传递给runApp。示例,
import 'dart:ui';
import 'package:flutter/material.dart';
void main() => runApp(_widgetForRoute(window.defaultRouteName));
Widget _widgetForRoute(String route) {
switch (route) {
case 'route1':
return SomeWidget(...);
case 'route2':
return SomeOtherWidget(...);
default:
return Center(
child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
);
}}
使用热重载:
将手机连接电脑或者打开模拟器
cd my_flutter/
bogon:my_flutter liuhe$ flutter attach
Waiting for a connection from Flutter on MI 8...
Done.
然后点击Debug App
Syncing files to device MI 8...
3,134ms (!)
To hot reload changes while running, press "r". To hot restart (and rebuild state),
press "R".
输入r进行热重载,输入R进行热重启(会重建状态)
文档:https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps