How to use shared preference on tap in flutter - 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

Related

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;
}

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

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);
}

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);
}

Shared preferences in flutter - error after flutter clear

i try to use shared preferences in flutter but i get this error and i tried to run flutter clear and still getting the same error
the error
ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Have you add the SharedPreferences dependecies in pubspec.yaml.If not here's how you do it:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.8
From the error message I believe SharedPreferences don't have getAll method. Here's some example how you read data from SharedPreferences :
getStringValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('stringValue');
return stringValue;
}
getBoolValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return bool
bool boolValue = prefs.getBool('boolValue');
return boolValue;
}
getIntValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return int
int intValue = prefs.getInt('intValue');
return intValue;
}
getDoubleValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return double
double doubleValue = prefs.getDouble('doubleValue');
return doubleValue;
}
After you adding a new package. You have to run
flutter pub get
Then rebuild you app.
for my case add setMockInitialValues({}) before sharedPreference.getInstance worked for me
SharedPreferences.setMockInitialValues({});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString(key, value);

can't delete key from shared preferences.string list

so newbie question but i think i have done everything in accordance with the documentation and i can't find the bug i have List string with shared preferences and 3 function laod save delete ,load and save work perfect but delete doing nothing without errors :/
List favorites=[];
#override
void initState(){
super.initState();
setState(() {
_loadList();
});}
_loadList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
favorites = (prefs.getStringList('myFavorites') ?? []);
});
}
_saveList(documentID) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('myFavorites', ['$documentID']);
_loadList();
}
_deleteList(documentID) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var list= prefs.getStringList('myFavorites');
list.remove(documentID);
_loadList();}
I couldn't find too many questions about it, I think my own stupidity forgets something. can someone help ?
I made a new list and add all keys to new list. deleted documentId in my new list and put the new list in place of myFavorites. Also works.