Reputation: 412
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
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
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
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
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