How can I save values to a list with SharedPreferences?
It's a simple list with a date and one value, for example, a list of my weight and sorting the list by date.
After searching a lot of articles here you are
For Saving data, must be converted to JSON
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, dynamic> user =
{'weight':[60,70],'height':[70,90]};
bool result = await prefs.setString('user', jsonEncode(user));
For Gettin data, must Deconverted from JSON
String userPref = prefs.getString('user');
Map<String,dynamic> userMap = jsonDecode(userPref) as Map<String, dynamic>;
or
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
Related
I make data connection with database to bring a list of data such as the following code:
var listDATA = [];
Future listDATAs() async {
api = '*************';
var response = await http.post(Uri.parse(api));
var responsebody = jsonDecode(response.body);
if (responsebody.length >0){
for (int i = 0; i < responsebody.length; i++) {
listDATA.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
}
return responsebody;
}else{
}
}
How can I store listDATA in Shared Preferences I need to save name and image ? Then recall it to display after storage
It's preferred not to store non-primitive data types in SharedPreferences as it supports only primitive data types by default. But still there is a way to do it.
you can store the response body of your API call without decoding JSON to a String value.
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an String value to 'response' key.
await prefs.setString('response', response.body);
if you have response types of List, you can use setStringList method
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
in this way you can store list value in shared preference
static setListValue(String key, List< ProductsModel > value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, jsonEncode(value.map((e) => e.toJson()).toList()));
}
her I make a standard method to store list values from any class by calling
setListValue('store_list', listData);
after that, you have to make a method for getting this list value
//getListValue
static Future<List<ProductsModel>?> getListValue(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final dataMap = jsonDecode(prefs.getString(key) ?? '[]') as
List<dynamic>;
return dataMap.map<ProductsModel>((item) {
return ProductsModel.fromJson(item);
}).toList();
}
after that, you can call this method like this
var listValue = await SPUtils.getListValue('store_list');
// for saving the list in shared preferences
final prefs = await SharedPreferences.getInstance();
prefs.setString("list",jsonEncode(listDATA));
// for getting the list from shared preferences
final prefs = await SharedPreferences.getInstance();
List listDATA = jsonDecode(prefs.get("list"));
You can follow those steps.
convert your object to map with toMap() method.
encode your map to string with encode() method.
Save the string to shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('key', encodedData);
// Fetch and decode data
final String musicsString = await prefs.getString('musics_key');
Example :
import 'dart:convert';
void main() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String encodedData = Music.encode([
Music(id: 1, ...),
Music(id: 2, ...),
Music(id: 3, ...),
]);
await prefs.setString('musics_key', encodedData);
// Fetch and decode data final String musicsString = await prefs.getString('musics_key');
final List<Music> musics = Music.decode(musicsString); }
class Music {
final int id;
final String name,
size,
rating,
duration, img; bool favorite;
Music({
this.id,
this.rating,
this.size,
this.duration,
this.name,
this.img,
this.favorite, });
factory Music.fromJson(Map<String, dynamic> jsonData) {
return Music(
id: jsonData['id'],
rating: jsonData['rating'],
size: jsonData['size'],
duration: jsonData['duration'],
name: jsonData['name'],
img: jsonData['img'],
favorite: false,
); }
static Map<String, dynamic> toMap(Music music) => {
'id': music.id,
'rating': music.rating,
'size': music.size,
'duration': music.duration,
'name': music.name,
'img': music.img,
'favorite': music.favorite,
};
static String encode(List<Music> musics) => json.encode(
musics
.map<Map<String, dynamic>>((music) => Music.toMap(music))
.toList(),
);
static List<Music> decode(String musics) =>
(json.decode(musics) as List<dynamic>)
.map<Music>((item) => Music.fromJson(item))
.toList(); }
I am using Firebase and SharePreferences to store some values after authentication. I get this error "Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
"
I am trying to store 2 Key value pairs as JSON into the sharedPreferences.
Here is my code. User.dart
class GoogleUser {
final String displayName;
final String photoUrl;
GoogleUser(this.displayName, this.photoUrl);
GoogleUser.fromJson(Map<String, dynamic> json)
: displayName = json['displayName'],
photoUrl = json['photoUrl'];
Map<String, dynamic> toJson() =>
{'displayName': displayName, 'phototUrl': photoUrl};
}
SharedPref.dart
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPref {
saveInfo(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
print("|||||||||||||||||||||||||||||||||||");
print(value);
}
deleteInfo(String key) async {
final prefs = await SharedPreferences.getInstance();
prefs.remove(key);
}
}
This the snippet which I use to save the user data, this is an file named as auth.dart, I get all the values push into sharedpreff.
void storeUserData(displayName, photoUrl) {
SharedPref sharedPref = SharedPref();
GoogleUser gUser = new GoogleUser(displayName, photoUrl);
String user = jsonEncode(gUser);
sharedPref.saveInfo('googleUser', user);
print("++++++++++++++++ Shared Prefs ++++++++++++++++++");
print(user);
}
This is the print output
This is retrieve info code, in a file login.dart
void getInfo() async {
final prefs = await SharedPreferences.getInstance();
print(prefs.getString('googleUser')!);
Map<String, dynamic> jsonData = jsonDecode(prefs.getString('googleUser')!);
var userData = GoogleUser.fromJson(jsonData);
print(
"--------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....----------------");
print(userData.displayName);
print(userData.photoUrl);
setState(() {
//(prefs.getString('googleUser'));
});
}
This is the print output for the first print statement in this method, The string appears different compared to how it got stored, and I get error on the line just after the first print statement. I am breaking my head on what is missing here.
I referred this article to write this code, https://protocoderspoint.com/store-data-model-object-data-in-sharedpreferences-flutter/
Any help is much appreciated for a newbie Flutter developer
I thinks its this line
prefs.setString(key, json.encode(value));
it should be:
prefs.setString(key, value);
since you already encoded the user to Srting in this line
String user = jsonEncode(gUser);
so basically this is my provider, what i want is how can i store the model data coming from provider to a shared preferences, and then how to decode it to show it in a bookmark page?
class bookmark extends ChangeNotifier{
int _count = 0;
List<bookmarkModel> bookM = [];
void addCount(){
_count++;
notifyListeners();
}
void addItems(bookmarkModel i){
bookM.add(i);
notifyListeners();
}
int get count => _count;
List<bookmarkModel> get bookMList => bookM;
}
here is my model:
import 'package:flutter/cupertino.dart';
class bookmarkModel{
String title;
String subtitle;
int num;
bookmarkModel({this.title, this.subtitle, this.num});
bookmarkModel.fromJson(Map<String,dynamic> json) :
title = json['title'],
subtitle = json['sutitle'],
num = json['num'];
Map<String, dynamic> toJson()=>{
'title':title,
'subtitle':subtitle,
'num': num
};
}
SharedPreferences should only be used to store small and simple values. It's not meant to be used as a Database.
You can use sharedPreferences to store bool, String, int and simple Lists (not lists of objects or maps). As far as I know, it even cannot store doubles.
Try using a SQflite or Hive (No-SQL) to store more complex or extensive data locally.
You already have toJosn and fromJson ready to use, you just need to convert bookM to a map josnEnode() and the get it back using josnDecode().
try the code below:
void saveBookmark() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String List = jsonEncode(bookM, toEncodable: (c)=> c.toJson());
await prefs.setString('BookMarkList', List);
}
void loadBookMark() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String saved = prefs.getString('BookMarkList');
final List<dynamic> decoded = jsonDecode(saved);
bookM = decoded.map((bookmark) => bookmarkModel.fromJson(bookmark));
}
I have been using shared_preferences to create and write in Json Files. The Problem i facing is i dont know how to create a Json Array and a List in shared_preferences.
I want to save and read a Json List.
read(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key));
}
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
}
remove(String key) async {
final prefs = await SharedPreferences.getInstance();
prefs.remove(key);
}
} ```
Example on DartPad.
Save a list to SharedPreferences with setStringList:
const String key = "users";
List<User> users = [User(name: "tester")];
List<String> jsonList = users.map((user) => user.toJson()).toList();
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList(key, jsonList);
Read a list from SharedPreferences with getStringList:
jsonList = prefs.getStringList(key);
users = jsonList.map((json) => User.fromJson(json)).toList();
The user class with json convert: JSON and serialization
class User {
String name;
int age;
User({
this.name,
this.age,
});
factory User.fromJson(String str) => User.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory User.fromMap(Map<String, dynamic> json) => User(
name: json["name"],
age: json["age"],
);
Map<String, dynamic> toMap() => {
"name": name,
"age": age,
};
}
Just map your json array to List<String> and after you can use the setStringList function provided in shared_preferences.dart
/// Saves a list of strings [value] to persistent storage in the background.
///
/// If [value] is null, this is equivalent to calling [remove()] on the [key].
Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);
When I open my apps, every time I need to wait for it loading the data from API. I want to save data on Local Storage temporary to make app works offline and also can load the data faster. I want to get data from api, json data and save them to local storage. Can I know what method or can use any package? Thanks in advance
I would recommend using SharedPreferences + JSON. For example, you may have a user object:
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};
}
Then what you need to do is:
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("user", jsonEncode(user));
And to recover the object:
SharedPreferences prefs = await SharedPreferences.getInstance();
User user = User.fromJson(jsonDecode(prefs.getString("user")));