I am pretty new to flutter and currently, I am writing an app that needs to store key-value pairs to disk and read it each time the app is open.
I based on this document, using shared preference package, and it works fine. However, debugging is not easy, I am used to web development, and the similar idea, localStorage can be easily accessed and edited in run time using almost any browser such as Chrome, this feature makes it easy to develop and debug.
So my question is that is there some equivalence in Flutter development that I can easily edit the shared preference storage? One of the most needed functionality is to clear everything in the shared storage, so I can repeat running a clean program and debug.
Right now I can only do this by writing a functional code like preferences.clear()
and running it once, which is a pain.
I am using VSCode Android AVD for Flutter development.
Thank you!
CodePudding user response:
So my question is that is there some equivalence in Flutter development that I can easily edit the shared preference storage?
Yes you can edit SharedPreferences values by the key which you set,
prefs.Set{anytype}(key,value); // will be used to set and update if key not found it will create else if found it will update to the same key.
updateSharedKeyVal(String prefKey, String prefValue) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(prefKey, prefValue);
// you can save or set value to persistent storage in the background
//prefs.setInt(prefKey, prefValue);
//prefs.setBool(prefKey, prefValue);
//prefs.setDouble(prefKey, prefValue);
}
updateSharedKeyVal("my_key_name","my_updated_value");
To Clear,
clearSharedPreference() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();
}
CodePudding user response:
I found a work-around, by directly modify the files in Android virtual machine: Go to Android View -> Tool Windows -> device file explorer.
Here you will see all the files on the virtual phone device.
Navigate to your app folder, normally in data/data/com.example.yourprojectname
In shared_prefs folder, there is an XML file containing all the local key-value pairs, you can directly modify it, or delete it here.
PS: At the current stage, if the Flutter app has heavy features based on local (SQLite and shared preference), Android Studio is a much better-developing tool than VSCode, for much better virtual device inspection.