Android工程集成flutter
2018-11-01 本文已影响358人
朱立志
Android工程集成flutter
官方方案
https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps
第一个步:
新建一个标准的APP工程testFlutterInAPP,APP目录下面通过命令创建flutter模块工程
flutter create -t module my_flutter
image.png编译flutter 代码生成Android的AAR文件
$ cd .android/
$ ./gradlew flutter:assembleDebug
AAR 文件生成到.android/Flutter/build/outputs/aar/目录下面
添加Host APP 依赖flutter module 模块,在setting.gradle 文件中加入
include ':app' // assumed existing content
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'my_flutter/.android/include_flutter.groovy' // new
))
app/build.gradle 增加对flutter 工程依赖
// testFlutterInAPP/app/build.gradle
dependencies {
implementation project(':flutter')
}
构建成功后,执行Android的run启动应用 ,点击打开flutter 。
image.png
Java 层代码
openFlutter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View flutterView = Flutter.createView(
MainActivity.this,
getLifecycle(),
"route1"
);
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(600, 800);
layout.leftMargin = 100;
layout.topMargin = 200;
addContentView(flutterView, layout);
}
});
flutter 代码
import 'dart:ui';
import 'package:flutter/material.dart';
void main() => runApp(_widgetForRoute(window.defaultRouteName));
Widget _widgetForRoute(String route) {
switch (route) {
case 'route1':
return new MyApp();
case 'route2':
return new MyApp();
default:
return Center(
child: Text('Unknown route1 : $route', textDirection: TextDirection.ltr),
);
}
return new MyApp();
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo 1111'
'Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
运行 flutter 工程 ,进入my_flutter 目录执行flutter run 命令
image.png即可启动flutter ,r == hot reload R == hot restart
q == quit d == detach,
或者启动Android应用调试
image.png但是,好像DEBUG无效??