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";
});
Related
I have a specific situation, so I need to put some data into a model with FutureProvider but I also need to have some additional fields that I want to change during the app, these fields need to be reactive. So this is my StateNotifier class:
class AirportNotifier extends StateNotifier<List<Airport>> {
AirportNotifier(super.state);
void updateIsActive(String value, int index) {
state[index].isActive = value;
}
}
My base class:
class Airport {
final String? name;
final String? description;
//final Uint8List? imageBytes;
String? isActive = "ve";
Airport({
this.name,
this.description,
});
factory Airport.fromJson(Map<String, dynamic> json) {
return Airport(name: json['name'], description: json['description']
//imageBytes: base64.decode(json['icon']),
);
}
}
Here I'm trying to create StateNotifier provider
final checkProvider =
StateNotifierProvider<AirportNotifier, List<Airport>>((ref) {
return AirportNotifier();
});
So, one way is to not use FutureProvider, in that way solution will be to send data like argument here
AirportNotifier(---);
But I have problem with converting Future<List> to List, every single solution on SO is just some basic things, I just need to convert this to List or to combine StateNotifier with FutureProvider on some way
I have this class to deserialize a paginated response from a server:
class PaginatedResponse {
final int current_page;
final dynamic data;
final String first_page_url;
final int from;
final int last_page;
final String last_page_url;
final String next_page_url;
final String path;
final int per_page;
final String prev_page_url;
final int to;
final int total;
PaginatedResponse({
this.current_page,
this.data,
this.first_page_url,
this.from,
this.last_page,
this.last_page_url,
this.next_page_url,
this.path,
this.per_page,
this.prev_page_url,
this.to,
this.total,
});
factory PaginatedResponse.fromJson(Map<String, dynamic> json) {
return json == null
? null
: PaginatedResponse(
current_page: json['current_page'],
data: json['data'],
first_page_url: json['first_page_url'],
from: json['from'],
last_page: json['last_page'],
last_page_url: json['last_page_url'],
next_page_url: json['next_page_url'],
path: json['path'],
per_page: json['per_page'],
prev_page_url: json['prev_page_url'],
to: json['to'],
total: json['total'],
);
}
Map<String, dynamic> toJson() => {
'current_page': current_page,
'data': data,
'first_page_url': first_page_url,
'from': from,
'last_page': last_page,
'last_page_url': last_page_url,
'next_page_url': next_page_url,
'path': path,
'per_page': per_page,
'prev_page_url': prev_page_url,
'to': to,
'total': total,
};
}
That same response is used for multiple different methods that expect different Types on the data property.
It would be ideal if I don't have to repeat all the other properties just to change the data type.
So how would I go about extending this class to allow for subclasses of this to have their proper Type in data?
Thank you!
To achieve that, you need to make PaginatedResponse with generic type of data. Like this:
class PaginatedResponse<DATA> {
final int current_page;
final DATA data;
...
The most difficult part is serialization/deserialization support of this by JSON frameworks. To me the best support of generics is implemented in built_value package. See here for complete example
i just wanted to ask since this thing got me confused, i am still beginner with OOP i started it with Java and now working with it in flutter, so basically when i use a model in flutter, am i using it to fetch data from an api or a web server, am i right? let's say it's like select .. from .. in SQL, is that right? for example here i have this model of location
import './location_fact.dart';
class Location {
final String name;
final String url;
final List<LocationFact> facts;
Location({this.name, this.url, this.facts});
}
so basically in final name and final url i am specifying which data to get from the api or the web server ( in the example i am just giving fake data which just data i am giving it manually without a third party api or web server ) so when i use these i am just like using select name, url from "apĂ®" ? is that the deal here? and when i am using the Location({this.name, this.url, this.facts}) am i specifying which data this model will take as a parameter ? and when i am using final am i like referring to the data that it won't be fetched again once it's fetched? and when i am using final list <LocationFact> facts; am i specifying that this data is going to take the facts only from the list or what? i know this is overwhelming but i am really beginner with dart and flutter generally, i appreciate anyone's help and thank you.
I think you're reading too much magic into the word "model". In the original "MVC" triad, there are Models (places to stash data), Views (basically Widgets in Flutter), and Controllers (generally buried in Widgets in Flutter, but can be and should be pulled out to testable and reusable logic). Does that help?
First of all if you fetching data from API it will return data in json format as json Object or json List after fetching data from API you can use json data or you can convert json Object to Plain Dart Object
To convert json data to Plain Dart Object you have to specify your model class.
Here is an example to design a model class
class Location {
String name;
String url;
List<Facts> facts;
Location({this.name, this.url, this.facts});
Location.fromJson(Map<String, dynamic> json) {
name = json['name'];
url = json['url'];
if (json['facts'] != null) {
facts = new List<Facts>();
json['facts'].forEach((v) {
facts.add(new Facts.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['url'] = this.url;
if (this.facts != null) {
data['facts'] = this.facts.map((v) => v.toJson()).toList();
}
return data;
}
}
class Facts {
String locationFact;
Facts({this.locationFact});
Facts.fromJson(Map<String, dynamic> json) {
locationFact = json['locationFact'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['locationFact'] = this.locationFact;
return data;
}
}
Here Location.fromJson() is an factory method to convert your json object to Plain Dart Object
For reference you should take a tour into the Official Documentation
Fetch Data From Network Flutter Documentation
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.
I am setting up my model classes to confirm to the docs for sqflite which suggest including a named constructor to convert to/from Maps to better handling of data between the classes and the DB. Every example I can find is very simple, with class properties all being simple data types.
Using the constructor and method shown below, converting to/from Map is quite simple when dealing with a class such as this.
class Human{
final String name;
final String height;
Final String weight;
Human({this.name, this.height, this.weight});
}
However, when you have a class where one of the fields is a bit more complex, I do not understand how to structure things within the named constructor and xxx method to return the map of data that I 'believe' I should get.
class Human{
final String name;
final String height;
Final String weight;
List<Child> children = [];
Human({this.name, this.height, this.weight, this.children});
}
Human({this.name, this.height, this.weight, this.children});
Human.fromMap(Map<String, dynamic> map)
: name = map['name'],
height = map['height'],
weight = map['weight'],
children = map['children'];
Map<String, dynamic> toMap() {
return {
'name': name,
'height': height,
'weight': weight,
'children': children,
};
}
The List children is the part I am struggling with. I believe you have to get each Child object ALSO converted to a map within the parent map, but am losing the battle here.
Is my approach way off here? Is there some other method I should be using to accomplish this?
Any assistance would be much appreciated.
Here I am explaining the following
How to convert a model object into Map to use with sqlite
How to convert a Map object from sqlite into a model class.
How to parse JSON reponse properly in flutter
How to convert a model object into JSON
All of the above questions has same answer. Dart has great support for these operations. Here I am going to illustrate it with a detailed example.
class DoctorList{
final List<Doctor> doctorList;
DoctorList({this.doctorList});
factory DoctorList.fromMap(Map<String, dynamic> json) {
return DoctorList(
doctorList: json['doctorList'] != null
? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
: null,
);
}
Map<String, dynamic> toMap() {
final Map<String, dynamic> data = Map<String, dynamic>();
if (this.doctorList != null) {
data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
}
return data;
}
}
The above DoctorList class has a member which holds a list of 'Doctor' objects..
And see how I parsed the doctorList.
doctorList: json['doctorList'] != null
? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
: null,
You may wonder, how the Doctor class may look like. Here you go
class Doctor {
final String doCode;
final String doctorName;
Doctor({this.doCode, this.doctorName});
factory Doctor.fromMap(Map<String, dynamic> json) {
return Doctor(
doCode: json['doCode'],
doctorName: json['doctorName'],
);
}
Map<String, dynamic> toMap() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['doCode'] = this.doCode;
data['doctorName'] = this.doctorName;
return data;
}
}
That's all. Hope you got the idea. Cheers!