最近flutter不是一般的火呀,但对于一些成熟的产品来说,完全摒弃原有App的历史沉淀,全面转向Flutter是不现实的。因此使用Flutter去统一Android、iOS技术栈,把它作为已有原生App的扩展能力,通过有序推进来提升移动端的开发效率
(1)创建flutter模块,创建module后会AS会自动进行flutter的相关配置
(2)将FlutterActivity添加到AndroidManifest.xml
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:theme="@style/FlutterTheme"
android:windowSoftInputMode="adjustResize" />
(3)跳转到flutter页面
startActivity(FlutterActivity.withNewEngine().initialRoute("route").build(this))
(4)你也可以使用缓存的FlutterEngine,可以减少加载延迟
在MyApplication中实例化一个FlutterEngine
class MyApplication : Application() {
lateinit var flutterEngine: FlutterEngine
override fun onCreate() {
super.onCreate()
flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)
}
}
然后在Activity中跳转
btn.setOnClickListener {
startActivity(FlutterActivity.withCachedEngine("my_engine_id").build(this))
}
注意:使用withCachedEngine()工厂方法时,请传递与缓存所需的ID相同的ID FlutterEngine
设置缓存引擎时也可以初始路由,修改MyApplication
flutterEngine = FlutterEngine(this)
flutterEngine.navigationChannel.setInitialRoute("route") //可以借此携带一些字符串数据,可传递到flutter页面
flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)
对应的dart
import 'dart:ui';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: _widgetForRoute(window.defaultRouteName),
);
}
}
//路由的选择
Widget _widgetForRoute(String route) {
switch (route) {
case 'route':
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter页面'),
),
body: Center(
child: Text('行走的猪蹄',
style: TextStyle(color: Colors.red),
textDirection: TextDirection.ltr),
),
),
);
default:
return Center(
child: Text('Unknown route: $route',
style: TextStyle(color: Colors.red),
textDirection: TextDirection.ltr),
);
}
}