Sonu Saini
Sonu Saini

Reputation: 2064

Want to get data from native android shared preferences

I don’t want to use method or event channel.

I am using the shared_preferences plugin in Flutter and want to access data from Android native shared preferences in Flutter code.

Here is my understanding:

1.Flutter uses shared_preferences to create a FlutterSharedPreference.xml file, while Android uses myprefs.xml. I would like to retrieve data from Android native shared preferences within my Flutter code.

  1. flutter add “flutter.” prefix in the key

Is there any way to get data or only create single file instead of 2 different.

Upvotes: 0

Views: 51

Answers (1)

João Davi
João Davi

Reputation: 1

You're correct that Flutter's shared_preferences plugin creates a separate file (FlutterSharedPreferences.xml) and prefixes keys with "flutter.". It doesn't directly access native Android's SharedPreferences.

While method channels are a common solution for accessing native data, there are ways to manage the migration and potentially avoid duplicate files, especially if you want to consolidate data.

I've written a detailed article on Medium that covers the process of migrating SharedPreferences from native Android/iOS to Flutter, including strategies to handle existing data and avoid conflicts:

How to migrate SharedPreferences from Android/iOS to Flutter

The article provides a comprehensive approach using method channels to facilitate the transfer. Even if your ultimate goal is to avoid continuous use of method channels after the initial migration, the techniques described there will help you access the native data to consolidate it into Flutter's shared_preferences. You can adapt the initial data retrieval steps and then implement a mechanism (like a one-time initialization flag) to prevent redundant reads from the native side on subsequent app launches. This will avoid the two file problem.

Upvotes: -1

Related Questions