How to store list of string with sharedpreferences in Flutter? - list

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

Related

delete one element in a list in sharedPreferences

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.

Comparing length of list in flutter bloc

I want to implement flutter bloc in my app. I want to compare the length of the list and trigger blocListener accordingly. But when using listenWhen, the parameter which it provides(previousState and currentState) both show the current length of the list. I expected that these two params will be giving different states through which I could compare the length of the list on different states.
BlocListener<ListBloc, ListCubitState>(
listener: (context, state){
print("new order");
},
listenWhen: (previous, current){
if(current.items.length > previous.items.length){
return true;
}
print(**current.items.length.toString()**);
print(**previous.items.length.toString()**);
return false;
},
My cubit class:
class ListBloc extends Cubit<ListCubitState>{
ListBloc(): super(ListCubitState(items: ["items", "items"]));
addItem() => emit(ListCubitState(items: addItemToList(state.items)));
removeItem() => emit(ListCubitState(items: removeItemToList(state.items)));
List<String> addItemToList(List<String> item){
List<String> newList = item;
newList.add("adsfasf");
return newList;
}
List<String> removeItemToList(List<String> item){
List<String> newList = item;
newList.removeLast();
return newList;
}
}
Could anyone suggest what's wrong in the code (or) Is there any other way to implement it?

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

How to convert list getting from future method to Map<String, dynamic>

I want to convert the list coming from getPosts method (getting result from the web json and stored in the posts list) to List
Post Class
class Post {
final int userId;
final String id;
final String title;
final String body;
Post(this.userId, this.id, this.title, this.body);
}
Future<List<Post>> getPosts() async {
var data = await http
.get("https://jsonplaceholder.typicode.com/posts");
var jasonData = json.decode(data.body);
List<Post> posts = [];
for (var i in jasonData) {
Post post = Post(i["userId"], i["id"], i["title"], i["body"]);
posts.add(post);
}
return posts;
}
I tried to put the result directly to this method
static List<Map> convertToMap({List myList }) {
List<Map> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}
but it's not working, I see this error
The argument type 'List<Map<dynamic, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.
Change List<Map> by List<Map<String, dynamic>>
static List<Map<String, dynamic>> convertToMap({List myList }) {
List<Map<String, dynamic>> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}

Adding elements to List in Flutter from For statement?

I'm receiving the following error while trying to add elements from my for loop to my List...
NoSuchMethodError: The method 'addAll' was called on null.
Receiver: null
Tried calling: addAll("LrWr826cd3Y")
Here is my code...
Future getData() async {
//Map videoId;
String url = 'https://Youtube API';
var httpClient = createHttpClient();
var response = await httpClient.read(url);
Map data = JSON.decode(response);
var videos = data['items']; //returns a List of Maps
List searchTitles;
List searchIds;
List searchImages;
for (var items in videos) {
//iterate over the list
Map myMap = items; //store each map
final video = (myMap['id'] as Map);
print(video['videoId']);
searchIds.addAll(video['videoId']);
final details = (myMap['snippet'] as Map);
final videoimage = (details['thumbnails'] as Map);
final medium = (videoimage['medium'] as Map);
}
setState(() { });
if (!mounted) return;
}
print(video['videoId']); successfully lists the 3 Youtube video ids as Strings. searchIds.addAll(video['videoId']); throws the error. I've tried both searchIds.add and searchIds.addAll. Where am I going wrong?
I would like to eventually push these lists to my List class here..
class CardInfo {
//Constructor
List id;
List title;
List video;
CardInfo.fromJson(List json) {
this.id;
this.title;
this.video;
}
}
You are not instantiating your searchIds object. add this
List searchIds = new ArrayList<>();
(Or)
List searchIds = new List();