最近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),
);
}
}