How to create more than one Shared-Preferences on Flutter? - dart

I created 2 shared preferences files. But automatically remove the first file. How to create multiple shared preferences files in Flutter?
First file
Future<bool> saveUrlPreference(String token,String refreshToken) async {
List<String> tokens = [token,refreshToken];
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList('tokens', tokens);
return pref.commit();
}
Second file
Future<bool> saveUrlPreference(String Url) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString("url", Url);
return pref.commit();
}

This is not yet supported
Upvote and follow https://github.com/flutter/flutter/issues/14337

Related

how to make singleton class with some initialization code?

I have tried the answers in here How do you build a Singleton in Dart?
but I can't achieve what I want. so basically I want to make a Shared Preference Service as a singleton class. currently my code is like this. this is just a regular class, not a singleton.
class SharedPreferenceService {
late SharedPreferences _prefs;
SharedPreferenceService() {
SharedPreferences.getInstance().then((value) => _prefs = value);
}
Future<void> setIntroPagesHaveBeenViewed() async {
await _prefs.setBool(SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED, true);
}
Future<bool> checkIfIntroPagesHaveBeenViewed() async {
return _prefs.getBool(SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED) ?? false;
}
}
I need a singleton class, but when the instance is initialize for the first time, I also need to initialize _pref , so then I can access that _pref on the methods
Your problem is that initialization is asynchronous.
That means that the first time the singleton instance is accessed, that access needs to be asynchronous too (and so does any further access which happens before the initialization completes). However, the usage pattern of a singleton like this is such that you don't know which access is the first. So you have to make every access asynchronous.
Example:
class SharedPreferenceService {
static final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<void> setIntroPagesHaveBeenViewed() async {
await (await _prefs).setBool(
SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED, true);
}
Future<bool> checkIfIntroPagesHaveBeenViewed() async {
return (await _prefs).getBool(
SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED) ?? false;
}
}
If all the methods are asynchronous anyway, that extra delay is not going to be a problem.
If you really, really only want to do that extra await if absolutely necessary,
you can cache the value, like you try to here:
class SharedPreferenceService {
static final Future<SharedPreferences> _prefsFuture = SharedPreferences.getInstance();
static SharedPreferences? _prefs;
Future<void> setIntroPagesHaveBeenViewed() async {
var prefs = _prefs ??= await _prefsFuture;
await _prefs.setBool(
SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED, true);
}
Future<bool> checkIfIntroPagesHaveBeenViewed() async {
var prefs = _prefs ??= await _prefsFuture;
return _prefs.getBool(
SharedPreferenceKey.INTRODUCTION_PAGES_HAVE_BEEN_VIEWED) ?? false;
}
}

How to add two number fetched from SharedPreferences in Flutter

I was trying to add two numbers say point1 and point2. These points are stored in SharedPreferences .
I have fetched the points using a function Future<int> fetchPoints which is in below.
Then I called this from another function
fetchPoints:
Future<int> fetchFromSps(String field) async {
SharedPreferences sp = await SharedPreferences.getInstance();
return sp.getInt(field);
}
GetPoints:
Future<void> setPoints() async{
int _newPoints=await ((await fetchFromSps('point1'))+(await fetchFromSps('point2')));
setState(() {
_totalPoints=_newPoints.toString();
});
}
setInSharedPreference:
void setInSharedPreference() async{
SharedPreferences prefs=await SharedPreferences.getInstance();
prefs.setInt('point1', 0);
prefs.setInt('point2',0);
}
The function setInSharedPreference is in another dart file,which contains main function
I need to add two points which is named 'point1 and 'point2' from shared preference
just call them from any method like this sample:
fetchTwoPoints() async {
final point1 = await fetchFromSps("point1");
final point2 = await fetchFromSps("point2");
setState(() {
_totalPoints= (point1 + point2).toString();
});
}
Update your setInSharedPreference method because you are using async you need to wait to store the data.
Future<void> setInSharedPreference() async{
SharedPreferences prefs=await SharedPreferences.getInstance();
await prefs.setInt('point1', 0);
await prefs.setInt('point2',0);
}

Get stored shared preference list and display in list view

Hi I'm having issue where getting the stored value from Shared Preference and displaying it. It giving Future doesn't contain length instance error. My code below.
Save Shared Preference Value Code
Future<String> saveSearchQuery(String squery) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if(prefs.getStringList("searchhistory") == null){
final List<String> recentSearch = [];
recentSearch.insert(0, squery);
prefs.setStringList("searchhistory", recentSearch);
}else{
final recentSearch = prefs.getStringList("searchhistory");
if(recentSearch.contains(squery)){
recentSearch.forEach((e) => print(e));
}else{
recentSearch.insert(0, squery);
}
prefs.setStringList("searchhistory", recentSearch);
}
return prefs.commit().toString();
}
Get Shared Preference Value Code
Future<dynamic> getSearchHistory() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List searchHistory = prefs.getStringList("searchhistory");
return searchHistory.toList();
}
Please help. Thank you.

Flutter: shared preferences

I have this function:
Future<String> load(SharedPreferences prefs, String fileName) async {
prefs = await SharedPreferences.getInstance();
String jsonString = prefs.getString(fileName) ?? "";
if (jsonString.isNotEmpty) {
return jsonString;
}else{
return ...
}
}
What should I return in the else case? I tried with "" but it doesn't work.
Shared Preferences
In Flutter, Shared Preferences are used to store primitive data (int, double, bool, string, and stringList). This data is associated with the app, so when the user uninstalls your app, the data will also be deleted.
Get the plugin
The shared_preferences plugin from pub is a wrapper around Android SharedPreferences and iOS NSUserDefaults. You can get this plugin by adding the shared_preferences line to your pubspec.yaml file in the dependencies section.
dependencies:
shared_preferences: '>=0.5.12+2 <2.0.0'
You can change the version number to whatever the current one is, but anything less than 2.0 should be compatible.
Import the package
In whichever file you need the Shared Preferences, add the following import:
import 'package:shared_preferences/shared_preferences.dart';
Reading and writing data
To get the shared preferences object you can do the following:
final prefs = await SharedPreferences.getInstance();
This will be used for all of the following examples.
int
read: final myInt = prefs.getInt('my_int_key') ?? 0;
write: prefs.setInt('my_int_key', 42);
double
read: final myDouble = prefs.getDouble('my_double_key') ?? 0.0;
write: prefs.setDouble('my_double_key', 3.14);
bool
read: final myBool = prefs.getBool('my_bool_key') ?? false;
write: prefs.setBool('my_bool_key', true);
string
read: final myString = prefs.getString('my_string_key') ?? '';
write: prefs.setString('my_string_key', 'hello');
stringList
read: final myStringList = prefs.getStringList('my_string_list_key') ?? [];
write: prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);
Removing data
You can remove any saved data by supplying the key name:
prefs.remove('my_int_key');
I rarely find a need to do that, though. I just overwrite the old data or ignore it. You shouldn't store any sensitive data in Shared Preferences.
See also
Shared Preferences Service in Flutter for Code Maintainability
Documentation: Storing key-value data on disk
What are the ?? double question marks in Dart?
How to create an empty list in Dart
The answer is "it depends". Namely, it depends on what exactly you are doing with the result of this function, and what a good empty default value means in that context.
Assuming you're decoding the returned JSON string into a Map<String, dynamic>, then a good default value might be the empty map. In that case, you could reformulate your function as follows:
Future<String> loadJSON(final String fileName) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String jsonString = prefs.getString(fileName);
if (jsonString != null && jsonString.isNotEmpty) {
return jsonString;
}
return "{}"; // default value
}
final String jsonString = await loadJSON("test.json");
final Map<String, dynamic> jsonData = json.decode(jsonString);
However, it probably makes more sense to reformulate this procedure as a slightly higher-level function returning actual map values:
Future<Map<String, dynamic>> loadData(final String fileName) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String jsonString = prefs.getString(fileName);
if (jsonString != null && jsonString.isNotEmpty) {
return json.decode(jsonString);
}
return Map(); // default value
}
final Map<String, dynamic> jsonData = await loadData("test.json");

Flutter Await Callback Not Give Any Response

I am still a beginner on dart flutter, now I am trying to retrieve data from the REST API and socket.IO. at this time I have a confusing problem, I have tried searching on the internet for 3 days, but there is no solution. I have async and await scripts, but the function I added await doesn't give any response and still pause.
it is assumed that I have two different files, the first is the main file and the second is the helper file.
main.dart
Future<List<ChatTile>> fetchChat(socketutil,id) async {
socketutil.join(id); //STACK IN HERE
SharedPreferences prefs = await SharedPreferences.getInstance();
String messagePrefs = prefs.getString('messagePrefs');
print("DUA");
return await compute(parseListChat, messagePrefs);
}
helper.dart
Future<void> join(String id_room) async {
String jsonData ='{"room_id" : "$id_room","user_id" : "5a91687811138e74009839c9","user_name" : "Denis Muhammad Ramdan","user_photo" : "photo.jpg","user_status" : "1"}';
socketIO.sendMessage("join", jsonData, null);
//subscribe event
return await socketIO.subscribe("updateMessageList", (result) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('messagePrefs', result);
print('SATU');
return await result;
});
}
my question is there something wrong with my code, and how is the best way?
many thanks,
I suggest you to add await_only_futures to your analyzer config
analysis_options.yaml
lint:
rules:
- await_only_futures
You also don't need to do return await something since your function already return a future, this is redondant.
And from what I see of the socketio subscribe method, it does not return the result like you expect but use a callback and does not return it (https://pub.dartlang.org/documentation/flutter_socket_io/latest/flutter_socket_io/SocketIO/subscribe.html)
to handle this you should use a Completer
final completer = Completer<String>()
socketIO.subscribe("updateMessageList", (result) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('messagePrefs', result);
socketIO.unSubscribe("updateMessageList");
completer.complete(result);
});
return completer.future;
you probably want to handle error when there is using completer.completeError(error)
Update
You can alos convert the subscription to a Dart Stream to handle more case.
StreamController<String> controller;
Stream<String> get onUpdateMessageList {
if (controller != null) return controller.stream;
constroller = StreamController<String>.broadcast(
onCancel: () => socketIO.unSubscribe("updateMessageList"),
);
socketIO.subscribe("updateMessageList", constroller.add);
return controller.stream;
}
Future<StreamSubscription> join(String id_room) async {
...
return onUpdateMessageList.listen((result) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('messagePrefs', result);
});
}

Resources