How to save a string in a Liststring in flutter? - flutter

Hello I don't find a solution to add a string in a liststring that I can save with shardpref.
I have a specific case where I use QR code reader, the output is a string that I want to store in a Liststring and save with sharedpref
Here is the part of the plugin who generate the String code of the QRcode:
void _onQRViewCreated(QRViewController controller) {
final channel = controller.channel;
controller.init(qrKey);
this.controller = controller;
channel.setMethodCallHandler((MethodCall call) async {
switch (call.method) {
case "onRecognizeQR":
dynamic arguments = call.arguments;
setState(() {
qrText = arguments.toString();
qrText is a String. I tried to change argments.toListstring(); but I have no output when I did this ...
Here is my save List function where I can't add qrText to the Stringlist
save_code() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setStringList("save_code",qrText); // qrText need to be a Stringlist
_my_save_code_list = prefs.getStringList("save_code");
} );
}
Thank you

Why do you want to use a StringList? If it is only the code you could also save it as a normal string, right? Or is the string too long to be a normal string?
-> I think you need to do it like this:
save_code() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> stringList = [];
stringList.add(qrText);
setState(() {
prefs.setStringList("save_code",stringList); // qrText need to be a Stringlist
_my_save_code_list = prefs.getStringList("save_code");
} );
}

Related

Flutter shared prefernce return NULL

I have next piece of flutter code, to get shared preference key-value
I do understand why _blueUriInit is always NULL
I assume that you are forgot to provide the value for that key before call to get its value, you need to first assign value to it first:
Future<bool> saveData(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(key, value);
}
and call it like this:
void initState() {
saveData('blueUri', 'test');
setState(() {
_blueUriInit = getValue('blueUri');
});
super.initState();
}
now next time you open your app, getValue should return you test.
you can create this function for setting value
static setUserID(String key, String value) async {
final SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setString(key, value);
}
Use case :
await SharedValue.setUserID("Email", "demo#gmail.com");
And For getting value from shared preference you can use this function
static Future<String?> getUserID(String key) async {
final SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getString(key);
}
Use case :
userName = await SharedValue.getUserID("Email");
First you need to setString with key and value (name is key)
Future setValue() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString("name", "Hitarth");
}
getString with key (here i took "name" as key)
Future getValue(String key) async {
final prefs = await SharedPreferences.getInstance();
String value = prefs.getString(key) ?? "NULL";
return value;
}
store in variable callin getValue
void initState() {
setState(() {
_blueUriInit = getValue("name");
});
super.initState();
}

Flutter, how to set and get list of values in shared preferences

I have SharedPreferencesHelper class where I stored simple data that I need.
I came across an issue. I need to store 3-4 strings in the list in shared preferences. How can I do the setter and getter for it?
SharedPreferencesHelper class:
class SharedPreferencesHelper {
static SharedPreferences? _preferences;
Future<void> init() async {
_preferences ??= await SharedPreferences.getInstance();
}
String get username => _preferences?.getString(keyUsername) ?? '';
set username(String value) {
_preferences?.setString(keyUsername, value);
}
// get aliases
List<String>? get aliases => _preferences?.getStringList(keyAliases);
// set aliases
}
You can do this to save list of string:
var pref = await SharedPreferences.getInstance();
pref.setStringList('someList',['1','2','3']);
and get it like this:
var result = pref.getStringList('someList');
if (result != null) {
print('result= $result'); //result= [1, 2, 3]
}
You can write the code like that :
class SharedPreferencesService {
SharedPreferencesServiceImpl(this.preferences);
final SharedPreferences preferences;
/// Static Variables
static const _userId = 'user_id';
#override
Future<String?> get userId async => preferences.getString(_userId);
#override
Future<void> setUserId(String value) async =>
await preferences.setString(_userId, value);
#override
Future<void> clear() async => await preferences.clear();
}
Moreover, you have to inject SharedPreferencesInstance in your getIt (recommended to use)
final getIt = GetIt.instance;
Future<void> setupExternals() async {
final prefs = await SharedPreferences.getInstance();
getIt.registerLazySingleton(() => prefs);
getIt.registerLazySingleton<SharedPreferencesService>(
getIt());
}

How can I make this work? My shared preferences seem to store the wrong value?

I have these functions to set, remove etc variables I want globally available. I fear it might be just a small mistake on my behalf. What can I do to fix this?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
You should also await when getting the value and for that, you should declare the function getUserId() as Future and also return the function value like this:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it

How to save a list with SharedPreferences?

I tried to save a List (which is called test)with two variables with SharedPreferences. I tried the code below, but I get some errors. Does anybody see the mistake i made? (I think it´s kind of an easy to fix mistake, but I´m a beginner and can´t find it ;)
int counter1 = 0;
int counter2 = 20;
String nameKey = "eins";
var test = [counter1, counter2];
#override
void initState() {
super.initState();
}
Future<bool> save() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return await preferences.setIntList(nameKey, test);
}
Future<List<int>> load() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getIntList(nameKey);
}
set() {
load().then((value) {
setState(() {
test = value;
});
});
}
Thanks in advance :)
Future<List<String>> load() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getStringList(nameKey);
}

Instance of 'Future<String>' instead of showing the value

Iam using flutter and I am trying to get a value from shared_preferences that I had set before, and display it in a text widget. but i get Instance of Future<String> instead of the value. here is my code:
Future<String> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = prefs.getString('patientPhone').toString();
print(patientPhone);
return patientPhone;
}
Future<String> phoneOfPatient = getPhone();
Center(child: Text('${phoneOfPatient}'),))
There is await missing before prefs.getString( and use setState() instead of returning the value. build() can't use await.
String _patientPhone;
Future<void> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = await /*added */ prefs.getString('patientPhone');
print(patientPhone);
setState(() => _patientPhone = patientPhone);
}
build() {
...
Center(child: _patientPhone != null ? Text('${_patientPhone}') : Container(),))
}
If you don't have the option to use await or async you can do the following.
getPhone().then((value){
print(value);
});
and then assign a variable to them. From that, you'll have the result from the value.