How to access android Shared preferences(using java) on the flutter end (using dart)?
559
Solution 1
What you can do is:
1. Set the name in getSharedPreferences
to "FlutterSharedPreferences"
.
getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE)
2. Always prefix "flutter."
in the key of any pair.
putString("flutter.test", "Hello")
Kotlin Code.
val prefs: SharedPreferences = getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE)
prefs.edit().putString("flutter.test", "Hello").apply()
3. Read the value like this in Flutter.
String test = (await SharedPreferences.getInstance()).getString("test"); //returns Hello.
Solution 2
if you use android java
on android side
Map<String, String> data = yourdata;
SharedPreferences preferences = this.getSharedPreferences("FlutterSharedPreferences",MODE_PRIVATE);
JSONObject jsonObject = new JSONObject(message);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString("flutter.msg",jsonString);
editor.apply();
on flutter side
SharedPreferences preferences = await SharedPreferences.getInstance();
if(preferences.containsKey('msg')){
final message = preferences.getString('msg');
Map data = json.decode(message);
}
Author by
Admin
Updated on December 01, 2022Comments
-
Admin over 1 year
I have tried to many days but getting null value on flutter side.
I have shared the code. Please let me know is there anything wrong?
I also refer the link How to access flutter Shared preferences on the android end (using java) but it it exact opposite my requirements.
MainActivity.java
SharedPreferences prefs = contextApplication.getSharedPreferences("preference", MODE_PRIVATE); //save in shared prefs prefs.edit().putString("hashMapEventsInBg_session", hashMapString).apply();
main.dart
SharedPreferences sp = await SharedPreferences.getInstance(); var demosession = sp.getString("hashMapEventsInBg_session");