What will be the name of SharedPreference created in flutter app? - flutter

I just new in flutter and coming from android,
In android we declare sharedPreference name like
SharedPreferences sp = Activity.this.getSharedPreferences("USER", MODE_PRIVATE);
by this in android USER.xml file was created,
So, what will be the name of sharedPreference in created by flutter app in this example?
how i store collection of data in sharedPreference,like
USER,
HOBBIES
TYPES,
etc
addIntToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('intValue', 123);
}
read data
getIntValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return int
int intValue = prefs.getInt('intValue');
return intValue;
}

You can take a look at the source code of the shared_preferences package:
// Line 37
private static final String SHARED_PREFERENCES_NAME = "FlutterSharedPreferences";
// ...
// Line 54
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
So the name is simply "FlutterSharedPreferences".
If you want to group entries by a model (e.g. User, HobbieType), you can add a prefix to each key:
addIntToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// Entries related to users
prefs.setInt('User_intValue', 123);
prefs.setString('User_strValue', "123");
prefs.setBool('User_boolValue', true);
// Entries related to hobbie types
prefs.setInt('HobbieType_intValue', 456);
prefs.setString('HobbieType_strValue', "456");
prefs.setBool('HobbieType_boolValue', false);
}

Related

Store data in dart/flutter

I am coding a to-do list app in flutter but every time I close the app, all my to-do's are gone, and none of them are stored. How do I stop them from disappearing every time I close the app?
Use sqlite or files. Please refer documentation on cookbooks for either approach.
https://docs.flutter.dev/cookbook/persistence
Your other option is to use an external database over the internet
To persist your data (todo list) you can either
store data on the users device
You can do this by using a local databases like sqflite, sqfentity, shared_preferences etc
or store the data on the server
Using this option you can either spin up your own server or use some quick serverless solutions like supabase or cloud firestore from firebase.
I recommend hive it’s very easy to use and it’s lightweigh.
In addition with all the other propositions, you can try Isar, which is a NoSQL local database that can be used for all platforms:
https://isar.dev/tutorials/quickstart.html
https://pub.dev/packages/isar
Apps generally store data in temporary storage which destroyed every time yo close the app. in order to save data permanently, you could use sqflite database or shared_preferences database
if you want use shared_preferences, you can do this:
first make class that call StorageManager:
import 'package:shared_preferences/shared_preferences.dart';
class StorageManager {
static Future<bool> saveData(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
if (value is int) {
prefs.setInt(key, value);
return true;
} else if (value is String) {
prefs.setString(key, value);
return true;
} else if (value is bool) {
prefs.setBool(key, value);
return true;
} else {
return false;
}
}
static Future<dynamic> readData(String key) async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
dynamic obj = prefs.get(key);
return obj;
}
static Future<bool> deleteData(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.remove(key);
}
static Future<void> reloadSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
}
}
then use it like this:
when you want save some thing in storage call this:
await StorageManager.saveData('some unique key', your int or string or bool value);
when you want read from storage:
var result = await StorageManager.readData('some unique key');
if (result != null) {
// use your value
} else {
// this means there is no result
}

How to retrieve data from Future object properly?

I'm using shared preferences. I want to get the list of strings, but for some reason it's always a null though it shouldn't be. I think I'm making a mistake in asynchronous stuff. Can somebody help me? With explanation if possible.
List<String> getSaved() {
List<String>? items;
Future<SharedPreferences> prefs = SharedPreferences.getInstance();
prefs.then((prefs) async {
items = prefs.getStringList('saved');
});
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}
Because you want the result when the future completed your function should be of type Future<List<String>> and you can use then or await knowing that items should be of the same type too
Future<List<String>> getSaved() async {
List<String>? items;
SharedPreferences prefs = await SharedPreferences.getInstance();
items = prefs.getStringList('saved');
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}

how to retrieve a value from shared preferences instantly? - FLUTTER

I'm trying to show a page as an initial login, this is only displayed when my switch value is set to true.
The switch value is stored with shared preferences but when I open the application it is not recovered, only after an application update is it actually recovered. how can i get it to be recovered instantly when i open my application?
below the code:
Future<bool> saveSwitchState(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("switched", value);
print('Switch Value saved $value');
return prefs.setBool("switched", value);
}
Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}
on another page then the value that is actually recovered:
if(AuthPage.authenticated == false && SettingsPage.switched == true ) {
yield ProfileNoAuth();
return; }
you can use dependency injection follow these steps :
get it package
create a Separate dart containing the following code file like this:
GetIt locator = GetIt.instance;
Future<void> setupLocator() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
locator.registerLazySingleton<SharedPreferences>(() => sharedPreferences);
}
call the setupLocator() method and wait for it in your main function
void main() async {
await setupLocator();
runApp(App());
}
access SharedPreferences Instance from anywhere like this:
locator();
now the SharedPreferences Instance if available anywhere in your project
please note that you dont have to wait for getting the Instance anymore, because you have only one Instance sharable across the application
bool getSwitchState() {
final prefs = locator<SharedPreferences>();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}

Flutter : How to use SharedPreference to get List<String>?

I've create an initState in my page and call callData to get favId (type : List) every I open this page. But, when the application start, my compiler show this error message :
_TypeError (type 'List<String>' is not a subtype of type 'String')
and this is my getData's function :
getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}
also this is my saveData's function :
void saveData() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList("id", favId);
}
How to fix this problem and I can call getData every I open this page in my application?
Thank you :)
if you want to save and retrieve List to and from SharedPreferences, you to use same key to save and retrieve the value.
here is a simple example,
const favKey = 'favoriteKey';
To save data,
void saveData(String favKey, List<String> favorites) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(favKey,favorites);
}
To retrive data,
getData(String favKey) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favKey);
}
Note: You need to use same key to set and get data using SharedPreference.
"id" is a String, you need to store a List<String> into setStringList
There are the steps if you want to add an item to the list:
List<String> ids = await getData(favId);
ids.add("id");
saveData(ids, favId);
then change the saveData() to
void saveData(ids, favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(ids, favId);
}
getData()
List<String> getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}

How to use shared preference on tap in flutter

I would like to save the id on tap the item for that I am using shared preference but unable to use the same id in entire application.
onTap: ()async{
var orderId = orderitems['order_id'];
print("my_orders_order_id :: "+orderId);
_loaded_my_orders_order_id = await _setOrderstatusId("my_orders_order_id", orderId);
//print(_setOrderstatusId);
if(_loaded_my_orders_order_id!=null){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyOrderDetailsPage(
)));
}
},
On tap it navigate to next page but in shared preference previous id was stored an it shows the previous details.
Just follow the following steps
if(_loaded_my_orders_order_id!=null){
// save the order_id to the shared prefs
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('order_id', _loaded_my_orders_order_id);
Navigator.push(context,MaterialPageRoute(builder: (context) => MyOrderDetailsPage()));
}
To fetch the saved order_id from shared preferences in the app anywhere,
// fetch the order_id to the shared prefs
SharedPreferences prefs = await SharedPreferences.getInstance();
int order_id=prefs.getInt('counter');
Then you can use it anywhere you want in the scope.
For using sharedpreferences in flutter you need to follow below steps :-
Here, data is id in your case.
step 1: Add dependencies to pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"
step 2: Save data
setID(int value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('ID', value);
}
step 3: Get data
getID() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return int
int intValue = prefs.getInt('ID') ?? 0;
return intValue;
}
Reference