Dart入门系列:
Flutter开发Dart极速入门 (基本类型)
Flutter开发Dart极速入门 (变量)
Flutter开发Dart极速入门 (函数)
Flutter开发Dart极速入门 (操作符与流程控制语句)
Flutter开发Dart极速入门 (异常)
Flutter开发Dart极速入门 (类和对象)
Flutter开发Dart极速入门 (泛型)
Flutter开发Dart极速入门 (异步详解)
Flutter开发Dart极速入门 (生成器)
Flutter开发Dart极速入门 (库的使用)
Flutter插件化开发注意事项(Packages与插件化开发)
Flutter在Android原生工程中的集成
在Android工程根目录的上一级目录创建Flutter工程,保证Flutter工程与Android工程在同一级。
- cd Android工程根目录的上一级
- 创建Flutter工程:flutter create -t module flutter工程名
// 这里建议使用命令的方式创建, AS直接创建工程出来的会有问题
C:\...\FlutterInAndroid\AndroidDemo>cd ..
C:\...\FtterInAndroid>flutter create -t module flutter_demo
cd到Flutter工程目录下的.android目录,执行gradlew脚本
- 注意:点后面是反斜杠
C:\...\FlutterInAndroid>cd flutter_demo
C:\...\FlutterInAndroid\flutter_demo>cd .android
C:\...\FlutterInAndroid\flutter_demo\.android>.\gradlew flutter:assembleDebug
首先,修改Android项目根目录下的setting.gradle:
include ':app'
//加入下面配置
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
'flutter_demo/.android/include_flutter.groovy'
))
然后,修改app下的build.gradle:
android {
...
defaultConfig {
...
minSdkVersion 16//至少16
...
}
...
//添加下面配置
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
}
...
dependencies {
...
//加入下面配置
implementation project(':flutter')
}
/**
* 创建view
*/
View flutterView = Flutter.createView(MainActivity.this, getLifecycle(), "r1");
/**
* 创建Fragment
*/
Fragment flutterFragment = Flutter.createFragment("r2");
可以通过window的defaultRouteName获取路由名称,依此进行判断并创建不同的Widget给Android工程调用。
void main() => runApp(selectWidget(window.defaultRouteName));
Widget selectWidget(String routeName) {
switch (routeName) {
case 'r1':
return MyFlutterView();
case 'r2':
return MyFlutterFragment();
default:
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Text(
'Unknow Route!',
style: TextStyle(color: Color(0xffff0000)),
),
),
),
);
}
}
首先在Flutter Module工程目录下执行flutter attach,开始监听flutter。
C:\...\FlutterInAndroid\flutter_demo>flutter attach
Waiting for a connection from Flutter on SCL AL00...
然后,在Android工程中运行程序,运行成功后可以在终端输入小写r热加载,大写R热重启。
C:\...\FlutterInAndroid\flutter_demo>flutter attach
Waiting for a connection from Flutter on SCL AL00...
Done.
Syncing files to device SCL AL00...