fluttersharedpreferencesproguardflutter-sharedpreferenceawesome-notifications

Proguard rules to avoid Shared Preferences Not Found in flutter


I use the awesome_notifications plugin in my Flutter app. In debug mode everything runs fine, but in production the app crashes at launch.

So I did bunch of testing and finally found out that in production, shrinkResources and minifyEnabled is set to true which is causing an error with the Shared Preferences giving the following error:

E/flutter ( 3523): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(SHARED_PREFERENCES_NOT_AVAILABLE, class F3.b isn't parameterized, sharedPreferences.get, null)

Then I messed around some proguard rules and found out that class F3.b without minification refers to com.google.common.reflect.TypeToken.

E/flutter ( 6248): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(SHARED_PREFERENCES_NOT_AVAILABLE, class com.google.common.reflect.TypeToken isn't parameterized, sharedPreferences.get, null)

As R8 code shrinking only happens in release build, I wasn't catching any errors in debug mode. So I disabled code shrinking and the app worked just fine in production.

So I want to know if there are any proguard rules to prevent Shared Preferences from getting code shrinked and avoid this issue while enabling shrinkResources and minifyEnabled.


Solution

  • After bunch of testing and research I got to know that the awesome_notifications plugin was using both com.google.common.reflect and com.google.gson.reflect for TypeToken but only has proguard rules to avoid R8 full mode code shrinking for the gson package.

    The R8 full mode is set to true by default now, hence this issue happens. See more on this here and here.

    So adding the below rules in the proguard-rules.pro file solved the issue.

    -keep class com.google.common.reflect.TypeToken
    -keep class * extends com.google.common.reflect.TypeToken