適用於flutter單獨開發,android項目單獨開發的場景
1:將flutter項目打包成aar文件,詳情見官方文檔:https://flutter.cn/docs/development/add-to-app/android/add-flutter-screen
2:在原生android項目文件中,項目根目錄app/build.gradle文件中添加以下模塊
String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"
repositories {
maven {
url '可以寫自己flutter項目的絕對路徑比如:d:\\flutter_pro\\build\\host\\outputs\\repo'
}
maven {
url 'http://download.flutter.io'
}
}
3:同樣在項目根目錄app/build.gradle文件中的 dependencies 模塊添加以下代碼
debugImplementation 'com.example.flutter項目名稱:flutter_debug:1.0'
profileImplementation 'com.example.flutter項目名稱:flutter_profile:1.0'
releaseImplementation 'com.example.flutter項目名稱:flutter_release:1.0'
4:同樣在項目根目錄app/build.gradle文件中的 android/buildTypes 添加以下代碼
profile {
initWith debug
}
ps:
1-4步在flutter生成aar文件完畢後,會在控制檯打印出以上配置信息,請留意
5:在項目根目錄app/src/main/AndroidManifest.xml中添加以下代碼到 application 模塊裏
<activity android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" />
6:讓項目自動下載依賴包
7:在android項目中想使用flutter的文件中引入包
import io.flutter.embedding.android.FlutterActivity;
8:調用flutter頁面代碼,調用邏輯按自己項目需求來
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("自己flutter項目的頁面路由如:/main")
//設置成"/",如果設置成/main,不是flutter頁面的根路由,則點擊物理返回按鍵的時候會出現先返回根路由然後返回android界面的bug
.build(this)
);
ps:
編譯報錯:在第5步中的 android:theme="@style/LaunchTheme" 出錯
在src/main/res/values文件夾添加styles.xml ,內容如下
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowFullscreen">true</item> </style> </resources>
繼續編譯,報錯,Cannot fit requested classes in a single dex file
網上搜索原因是:
原因:項目貌似有點大,已經超過65k個方法。一個dex已經裝不下了,需要個多個dex,也就是multidex ,因爲Android系統定義總方法數是一個short int,short int 最大值爲65536。
一臉懵逼,明明自己是寫的個原生android demo項目,整個頁面就一個按鈕
按照提示
在 app 的 build.gradle 文件中(原文地址:https://blog.csdn.net/MRYZJ/article/details/103463212)
android {
defaultConfig {
···
// 這裏添加
multiDexEnabled true
}
}
dependencies {
// 引入support支持庫的multidex庫
implementation 'com.android.support:multidex:1.0.3'
//或androidx支持庫的multidex庫
implementation 'androidx.multidex:multidex:2.0.1'
}
運行,成功,點擊按鈕能正常出現flutter頁面,但是中間會有一段黑屏時間,稍後解決,至少項目能夠正常運行了
ps:
黑屏解決方案,網上很多,大概思路就是將主題設置爲白色或者透明即可
代碼可以修改爲(將頁面先初始化,調用的時候直接使用即可):
Intent demo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
demo = FlutterActivity
.withNewEngine()
.initialRoute("/main")
.build(this);
}
public void getflutter(View view) {
if(null == demo){
Toast.makeText(this, "未找到flutter頁面", Toast.LENGTH_SHORT).show();
}else {
startActivity(demo);
}
}