You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中避免Shared Preferences被混淆的ProGuard规则求助

解决Flutter生产环境开启混淆后SharedPreferences与TypeToken相关崩溃问题

当Flutter应用开启shrinkResources和minifyEnabled后,出现PlatformException(SHARED_PREFERENCES_NOT_AVAILABLE, class com.google.common.reflect.TypeToken isn't parameterized)报错,根源是R8混淆破坏了com.google.common.reflect.TypeToken的泛型参数化信息,导致SharedPreferences无法正常解析类型。

在Android项目的proguard-rules.pro文件中添加以下规则,即可在保留混淆优化的同时避免该问题:

# 保留com.google.common.reflect.TypeToken及其泛型相关方法,避免混淆破坏参数化信息
-keep class com.google.common.reflect.TypeToken
-keep class * extends com.google.common.reflect.TypeToken
-keepmembers class com.google.common.reflect.TypeToken {
    <init>(java.lang.reflect.Type);
    java.lang.reflect.Type getType();
}

# 确保SharedPreferences核心类不被混淆
-keep class io.flutter.plugins.sharedpreferences.** { *; }
-keep class androidx.preference.** { *; }

规则说明:

  1. 前三条规则保留TypeToken类及其子类,同时保留其构造方法和getType()方法,确保泛型类型信息在混淆后依然可被正确识别。
  2. 后两条规则保留Flutter SharedPreferences插件和AndroidX Preference相关类,避免核心逻辑被混淆破坏。

添加规则后重新构建生产包,即可解决启动崩溃问题。

内容的提问来源于stack exchange,提问作者OutdatedGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:12:03