delete one element in a list in sharedPreferences - list

I'm trying to delete an element in my favoriteList here but this doesn't seem to be working. I've looked on the web but couldn't find anything related to this. They were all about how to clear sharedPreferences or delete a key.
Future<void> removeFav(String articleId) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
favoriteList = prefs.getStringList('favoriteList');
if (favoriteList != null) {
await prefs.remove('${favoriteList!.where((id) => id == articleId)}'); //I'm guessing id here returns an element of this list..??
print('unfavorited');
setState(() {
isFavorite = false;
});
} else {
print('favoriteList was null');
}
}

You need to first remove the item from the list:
SharedPreferences prefs = await SharedPreferences.getInstance();
// get the list, if not found, return empty list.
var favoriteList = prefs.getStringList('favoriteList')?? [];
// remove by articleId
favoriteList.removeWhere((item) => item == articleId);
Then, saved the changed favoriteList back to sharedPreferences:
prefs.setStringList('favoriteList', favoriteList);

You should do these steps to save List of object in SharedPreferences:
convert your object to map → toMap() method
encode your map to string → encode(...) method
save the string to shared preferences
for restoring your object:
decode shared preference string to a map → decode(...) method
use fromJson() method to get your object
So in this case I think you should restore the list from shared preference and modify list and then save new list in shared preference.

Related

How to store list of string with sharedpreferences in Flutter?

I've a list of string that I've insert into a ListView in Flutter:
How can I store the list with sharedPreferences and use it in the ListView?
Declare your variables
List<Todo> list = new List<Todo>();
SharedPreferences sharedPreferences;
Save data into SharedPreferences after converting to json
void saveData(){
List<String> stringList = list.map(
(item) => json.encode(item.toMap()
)).toList();
sharedPreferences.setStringList('list', stringList);
}
Load data from SharedPreferences and convert back
void loadData() {
List<String> listString = sharedPreferences.getStringList('list');
if(listString != null){
list = listString.map(
(item) => Todo.fromMap(json.decode(item))
).toList();
setState((){});
}
}

How to convert or equalize Query<Map<String, dynamic>> to List

I have BrandList in my Firebase like this;
How can I convert or equalize this Firebase List to List.
I tried this;
var brandsRef = _firestore.collection("vehicles1").where("Brands");
List brandsList = brandsRef;
But I got this error "A value of type 'Query<Map<String, dynamic>>' can't be assigned to a variable of type 'List'."
You need to use the document Id to get the query and then you can get the data which returns a Map.
From that Map, you can supply the key to retrieve the value. In this case, the key is "Brands".
var brandsQuery = await _firestore.collection("vehicles1").doc(document Id).get();
List brandList = brandsQuery.data()["Brands"];
First I would suggest to create a model of your class Brand in addition to the jsonSerialization classics:
class Brands {
Brands({this.brandName});
List<String> brandName;
Map<String, dynamic> toMap() {
return {
'Brands': brandName,
};
}
factory Brands.fromMap(Map<String, dynamic> map) {
return Brands(
brandName: List<String>.from(map['Brands']),
);
}
String toJson() => json.encode(toMap());
factory Brands.fromJson(String source) => Brands.fromMap(json.decode(source));
}
Then you need to add a few steps to the way you retreive elements:
var response = _firestore.collection("vehicles1").where("Brands").get();
final results =
List<Map<String, dynamic>>.from(response.docs.map((e) => e.data()));
Brands brands =
results.map((e) => Brands.fromMap(e)).toList();

Flutter : how save list of dynamic to shared preference

I am trying to save a list of data to shared preference and read these articles but don't works with me :
Flutter save List with shared preferences
Shared Preferences in Flutter cannot save and read List
I have this list :
var list =[
{
"id" : 1,
"name" : "ali"
},
{
"id" : 2,
"name" : "jhon"
}
];
I tried this :
setList() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
prefs.setStringList('list', list);
}
I get this error : The argument type 'List<Map<String, Object>>' can't be assigned to the parameter type 'List<String>'
The error occurs because your list is of type Map<String, Object> and not a String. To fix this you can use jsonEncode method which converts it into a String
Future<void> setList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String> jsonList = list.map((item) => jsonEncode(item)).toList();
prefs.setStringList('list', jsonList);
}
If you now want to retrieve this list you have to use jsonDecode to convert it back to a Map<String, Object>.
List<Map<String, Object>> getList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String> jsonList = prefs.getStringList('list')
final List<Map<String, Object> list = jsonList.map((item) => jsonDecode(item)).toList();
return list;
}

Flutter FireStore empty list

I'm trying to read the ID of each doc in a collection. As I can saw, doc.id is a string, and it has the value name for each doc. So I just tried to add that value to a list, for later pass it to a DropDownButton. But for some reason, the list return null.
List<String> readthishit() {
List<String> ex;
FirebaseFirestore.instance
.collection('Enrollment')
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
ex.add(doc.id);
})
});
return ex;
}
What's happening?
You need to use the await keyword & wait for the result from Firebase.
Currently, you are sending a call to the Firebase but, before the result from Firebase, your code is returning the null list ex.
Future<List<String>> readThisShit() async {
List<String> ex = <String>[];
final querySnapshot = await FirebaseFirestore.instance
.collection('Enrollment')
.get();
querySnapshot.docs.forEach((doc) {
ex.add(doc.id);
});
return ex;
}
Also, I think you should use lowerCamelCase notation for your method names. So, readthisshit will become readThisShit.

Firebase python - How to check if field (property) exists in doc

We have read a document from firebase using Python.
doc_ref = db.collection(u'collection_name').document(collection_abc)
doc_fetched = doc_ref.get()
if (doc_fetched.exists):
if (doc_fetched.get('doc_field')):
We get the following error
KeyError("'doc_field' is not contained in the data")
How do we check if doc_field exists in doc_fetched? This document might have some fields populated, and some not populated at the time of read (by design).
We also tried the following with the same error.
if (doc_fetched.get('doc_field') != null):
As you can see from the API documentation for DocumentSnapshot, there is a method to_dict() that provides the contents of a document as a dictionary. You can then deal with it just like any other dictionary: Check if a given key already exists in a dictionary
To solve this, you can simply check the DocumentSnapshot object for nullity like this:
var doc_ref = db.collection('collection_name').doc(collection_abc);
var getDoc = doc_ref.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
if(doc.get('yourPropertyName') != null) {
console.log('Document data:', doc.data());
} else {
console.log('yourPropertyName does not exist!');
}
}
})
.catch(err => {
console.log('Error getting document', err);
});
Or you can use to_dict() method as in the #Doug Stevenson answer