Flutter : how save list of dynamic to shared preference - list

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

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

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.

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

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

Flutter - Fill future list from json

I want to fill a list from json.
Future<List<Titles>> fetchTitle() async {
String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url,headers: {'Content-Type': 'application/json'});
return titlesFromJson(utf8.decode(response.bodyBytes));
How to fill below list using fetchTitle method. I want to add "title" item from json.
final List myLists = [];
Expanded(
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1,
padding: EdgeInsets.only(left: 20, top: 20, right: 20),
children:List.generate(myLists.length, (index) {
return InkWell(
From the official documentation this is the way on how to fetch data from json and convert the response to list of model:
1- create a model for the post
class Post {
int userId;
int id;
String title;
String body;
Post({this.userId, this.id, this.title, this.body});
Post.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}
2 - import http package and fetch post from the link https://jsonplaceholder.typicode.com/posts
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts(http.Client client) async {
final response = await client
.get('https://jsonplaceholder.typicode.com/posts');
return parsePosts(response.body);
}
3 - Use the method that you define on your model to create a list that contain posts
import 'dart:convert';
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}
4 - to make a test that your code work, create a simple async main method that call fetchPosts with the await prefix because fetchPosts return a Future so if you don't use await you will get a future and not the List
void main() async {
List posts = await fetchPosts(http.Client());
// this will print the id and the title of posts
posts.forEach((post) => print('Post id: ${post.id} | Post title: ${post.title}'));
}
I hope this help!
To add the JSON result to a list, you may need to wait for the response and add it to the List. Since fetchTitle() method returns Future<List<Titles>>, when you await for it, you will get a List<Titles> which can be assigned to your myList.
myList = await fetchTitle();
Since we are using await, we may need to mark the method using async keyword.
void main() async {
List myList = [];
myList = await fetchTitle();
print(myList);
}