jepbura
jepbura

Reputation: 412

How to access a shared prefrences create in flutter from java code?

I create a SharedPreferences in flutter and I want to use it in android Native code in my project. How can I do that?

Upvotes: 5

Views: 2395

Answers (4)

eko
eko

Reputation: 672

Step By Step

1st Flutter Part

here you assign a value

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

final SharedPreferences prefs = await _prefs;
  await prefs.setString("SharedPrefKey", definition)

then you can use it in flutter where ever you want

String stringFromShared;

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

stringFromShared = prefs.getString("SharedPrefKey");

2nd Android Part

private SharedPreferences sharedPreferences;


sharedPreferences = getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE);
    sharedPreferences.getString("flutter." + "SharedPrefKey", "");

the key point here is usage of prefix "flutter."

Upvotes: 3

Elijah
Elijah

Reputation: 2213

For the noobs out here,

import android.content.SharedPreferences
...
var PRIVATE_MODE = 0
val mPrefs = getSharedPreferences("FlutterSharedPreferences", PRIVATE_MODE)
mPrefs.getString("flutter." + "key", "")

Upvotes: 8

Md Khairul Islam
Md Khairul Islam

Reputation: 627

Add this to your code. It will work.

SharedPreferences mPrefs = context.getSharedPreferences("FlutterSharedPreferences", context.MODE_PRIVATE);
String value = mPrefs.getString("flutter." + "YourSharedpreferencekey", "");

Upvotes: 11

Taym95
Taym95

Reputation: 2510

Dart sharedPreference use native java code which means they are using the same sharedPreferences, you can access that sharedPreferences key in Android by calling sharedPreferences from native code (Java or Kotlin).

Upvotes: 3

Related Questions