List<Data> datas = [];
Future<List<Data>> getData() async {
final response =
await http.get('https://iptv-org.github.io/iptv/index.country.m3u');
final m3u = await M3uParser.parse(response.body);
for (final entry in m3u) {
Data data = Data(entry.title, entry.attributes['tvg-logo'], entry.link,
entry.attributes['tvg-language'], 'false');
datas.add(data);
}
return datas;
}
class Data {
String title;
String logo;
String url;
String language;
String isFavorite = 'false';
Data(this.title, this.logo, this.url, this.language, this.isFavorite);
}
Everytime I get the data from the url, then how I gonna save the list of Data object? Can I save the data using sharedPref?
for complicated data its recommended to use the database. you can use SqfLite package as a database. but u can also use shared Preferences too. for creating Model use quicktype.io it will create your model with several useful methods such as toJson and fromJson. it will also generate fromRawJson and toRawJson. these two methods work with String. you can convert your model to string and stored to SharedPreferences and when you need it again take it and convert it to model.
Related
i want save list of object in local memory by shared_preferences my Model :
class Vehicle {
final String vehicleId;
final String vehicleType;
Vehicle({
this.vehicleId,
this.vehicleType,
});
}
after when i search about this i found half-solution :) to convert to List<String> and add this to my class :
factory Vehicle.fromJson(Map<String, dynamic> vehicleJson){
return new Vehicle(
vehicleId: vehicleJson['vehicleId'],
vehicleType: vehicleJson['vehicleType'],
);
}
Map<String, dynamic> toJson(){
return {
'vehicleId': this.vehicleId,
'vehicleType' : this.vehicleType,
};
}
but i can't found how can i save and get it :(
sorry my English not good
Actually you cannot save a list of object with shared preferences but you can encode each object into a string and save it using setStringList() function
Example:
List<String> vehiculesEncoded = [];
vehicles.forEach((vehicule) {
vehiculesEncoded.add(vehicule.toJson());
});
sharedPreferences.setStringList("myAmazingListOfVehicules", vehiculesEncoded);
this type of array you have & you want to store it in session
List<Vehicle> arrayVehicle = [ your data ];
for that you have to convert array into json string by doing this
String strTemp = json.encode(arrayVehicle);// store this string into session
whenever you want to retrive it just decode that string
List<Vehicle> arrayVehicle = json.decode(yourSessionValue)
I was wondering how I can read from a firebase database once. I want to be able to read from a document that has the same ID as the user that's logged in, via the firebase authentication, and then return the string of the user's name.
Right now I am getting 3 errors on line 12 under the get method
Function expressions can't be named
Expected an identifier
The getter '(' isn't defined for the type 'DocumentRefence<Object?>'
class DatabaseService {
final CollectionReference usersCollection = FirebaseFirestore.instance.collection("users");
final String uid;
DatabaseService(this.uid);
Future<String> getUserName() async {
String name = '';
var document = await usersCollection.doc(uid);
document.get() => then((doc) {
name = doc('name');
});
return name;
}
}
async/await should use of api calls not on the database path reference.
Just make sure of the snapshap.data() is correct, otherwise you can use my code as a reference.
Future<String> getUserName() async {
var document = usersCollection.doc(uid);
var snapshot = await document.get();
Map<String, dynamic> data = snapshot.data();
name = data['name'];
return name;
}
https://api.covid19api.com/summary
This is the API I am using now I can fetch the global data by the below code I want to fetch data of a single Country(India) by the same method. If there is no method by which I can get the data then if I use "https://api.covid19api.com/total/dayone/country/India" then how to get the daily confirmed cases.?
class GlobalSummaryModel{
final int newConfirmed;
final int totalConfirmed;
final int newDeaths;
final int totalDeaths;
final int newRecovered;
final int totalRecovered;
final DateTime date;
GlobalSummaryModel(this.newConfirmed, this.totalConfirmed, this.newDeaths, this.totalDeaths, this.newRecovered, this.totalRecovered, this.date);
factory GlobalSummaryModel.fromJson(Map<String, dynamic> json){
return GlobalSummaryModel(
json["Global"]["NewConfirmed"],
json["Global"]["TotalConfirmed"],
json["Global"]["NewDeaths"],
json["Global"]["TotalDeaths"],
json["Global"]["NewRecovered"],
json["Global"]["TotalRecovered"],
DateTime.parse(json["Date"]),
);
}
}
Please provide me the code if you can that will be more helpful for me I am new in fetching data from the rest API.
The API also returns a Countries field in the response, which contains data for India. You can extract that data like so:
final countries = json["Countries"];
final Map<String, dynamic> indiaSummaryData = countries.firstWhere((map) {
return map["CountryCode"] == "IN";
});
How do we store model data to flutter secure storage... or does it supports it?
I have a model like this... I load data from my API to this model... once I have data, I wanted to save it to the flutter secure storage and vice versa(load entire data to model from flutter secure storage)...
class MyUserModel {
MyUserModel({
this.authKey,
this.city,
this.contact,
this.email,
this.isContact,
this.userId,
});
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
}
Of course, I know we can read and write data like below... I am just checking if there is a way where we can directly write it from the model...
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// Create storage
final storage = new FlutterSecureStorage();
// Read value
String value = await storage.read(key: key);
// Write value
await storage.write(key: key, value: value);
I saw hive supports this feature out of the box but I realized that it takes little time (2-3 sec) for initialization also Author is working on an alternative to hive due to two major blocks... the new database called Isar which clears all roadblock but it is still in development...
if it is possible then please share the sample code...
to save the object:
convert your object to map with toMap() method
serialize your map to string with serialize(...) method
save the string into secure storage
for restoring your object:
deserialize secure storage string to a map with deserialize(...) method
use fromJson() method to get your object
by that, you will serialize your data into a string and save and retrieve them.
class MyUserModel {
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
MyUserModel({
required this.authKey,
required this.city,
required this.contact,
required this.email,
required this.isContact,
required this.userId,
});
factory MyUserModel.fromJson(Map<String, dynamic> jsonData) =>
MyUserModel(
authKey: jsonData['auth_key'],
city: jsonData['city'],
contact: jsonData['contact'],
email: jsonData['email'],
isContact: jsonData['is_contact'] == '1',
userId: jsonData['user_id'],
);
}
static Map<String, dynamic> toMap(MyUserModel model) =>
<String, dynamic> {
'auth_key': model.authKey,
'city': model.city,
'contact': model.contact,
'email': model.email,
'is_contact': model.isContact ? '1' : '0',
'user_id': model.userId,
};
static String serialize(MyUserModel model) =>
json.encode(MyUserModel.toMap(model));
static MyUserModel deserialize(String json) =>
MyUserModel.fromJson(jsonDecode(json));
}
Usage:
final FlutterSecureStorage storage = FlutterSecureStorage();
await storage.write(key: key, value: MyUserModel.serialize(model));
MyUserModel model = MyUserModel.deserialize(await storage.read(key: key));
You can do this by encoding your Model into json saving it in Secure Storage and then decode the json and get the model back.
// Saving model into Storage
static Future<void> setMyUserModel(MyUserModel user) async {
await const FlutterSecureStorage().write(
key: 'user', value: user.toRawJson());
}
// Getting model from storage
static Future<MyUserModel> getMyUserModel() async {
return MyUserModel.fromRawJson(
await const FlutterSecureStorage().read(key: 'user') ??
'{}');
}
And of course you need to implement fromRawJson() and toRawJson() inside your model.
Sorry for the late reply :P.
To do this, encode your model into JSON and store it in secure storage. Later, decode the JSON to retrieve the model.
final storage = FlutterSecureStorage();
static const String modelData = "modelData";
// Saving model into Storage
static Future<void> setModel(user) async {
final jsonDataEncoded = jsonEncode(jsonData);
await storage.write(key: modelData , value: jsonDataEncoded);
}
//call this when you want to store your data to secured storage
ClassName.setModel(decodedResponse);//decode your json and send it here
//to read data from the local storage || secured storage
static Future<MyModel> getDataFromLocalStorage() async {
final jsonModel = await storage.read(key: modelData);
final jsonData = jsonDecode(jsonModel.toString());
final items = List.from(jsonData);
dataList = items.map((e) => MyModel.fromJson(e)).toList();
return dataList;
}
I am new in Flutter, this is my first project in Flutter. I want to do a project that once data are loaded from API, they're cached in the device. Next time it can be loaded very fast even if my device is offline. I here that can using Dio package with dio cache manager package for caching server's json response. And then using cache image package to cache images. Anyone can give me some example how to write the code? Thanks in advance
Another best way for caching in flutter is the use of the hive. And it retrieves data faster than Sqflite and Shared preferences
For example, you can check this GitHub repo:https://github.com/shashiben/Anime-details
This will show how to cache the rest API data into the hive and for the next time it will show data from the hive.
I think this answer helped you
Yeah i'd recommend the sqflite package for flutter, i've just figured out how to use it to solve this same issue! I learnt it using this YouTube video: https://youtu.be/1BwjNEKD8g8.
Try shared preferences https://pub.dev/packages/shared_preferences,
Just Decode your response as string and save to sharePreference,
and Encode that String to Object when you need.
import 'package:shared_preferences/shared_preferences.dart';
//storing response as string
SharedPreferences sharedPref = await SharedPreferences.getInstance();
Map decode_options = jsonDecode(jsonString);
String user = jsonEncode(User.fromJson(decode_options));
sharedPref.setString('user', user);//storing
//getting string and converting into Object
SharedPreferences sharedPref = await SharedPreferences.getInstance();
Map userMap = jsonDecode(sharedPref.getString('user')); //retriving
var user = User.fromJson(userMap);
class User {
final String name;
final String age;
User({this.name, this.age});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return new User(
name: parsedJson['name'] ?? "",
age: parsedJson['age'] ?? "");
}
Map<String, dynamic> toJson() {
return {
"name": this.name,
"age": this.age
};
}
}