in this part of my code await webApi.getKeywords(); return array which that can get from server, now when i try to return that i get error:
type 'List<dynamic>' is not a subtype of type 'String'
get data from server code:
Future<List<KeywordsResponse>> _getKeywords(BuildContext context) async {
try {
final webApi = Provider.of<WebApi>(context);
final response = await webApi.getKeywords();
List<KeywordsResponse> list = List();
if (response.statusCode == 200) {
list = (json.decode(response.body) as List)
.map((data) => new KeywordsResponse.fromJson(data))
.toList();
return list;
} else {
throw Exception('Failed to load photos');
}
} catch (error) {
print(error);
return null;
}
}
KeywordsResponse class:
#JsonSerializable(nullable: true)
class KeywordsResponse{
#JsonKey(name:'id')
final int id;
#JsonKey(name:'title')
final String title;
#JsonKey(name:'description')
final String description;
KeywordsResponse(this.id, this.title, this.description);
factory KeywordsResponse.fromJson(Map<String, dynamic> json) => _$KeywordsResponseFromJson(json);
Map<String, dynamic> toJson() => _$KeywordsResponseToJson(this);
}
return of response.body:
[
{
"id": 1,
"user_id": 1,
"title": "asdasdasd",
"description": "asdasdasd",
"type": "post",
"slug": "asdasdad",
"featured_images": {
"images": {
"300": "/uploads/post_images/2019/300_1573573784.png",
"600": "/uploads/post_images/2019/600_1573573784.png",
"900": "/uploads/post_images/2019/900_1573573784.png",
"original": "/uploads/post_images/2019/1573573784.png"
},
"thumbnail": "/uploads/post_images/2019/300_1573573784.png"
},
"lang": "fa",
"visit": 0,
"categories": [
{
"id": 1,
"title": "aaaaaaa",
"lang": "fa",
"parent": 0,
"pivot": {
"contents_id": 1,
"content_categories_id": 1
}
}
]
},
{
"id": 2,
"user_id": 1,
"title": "asdasdasd",
"description": "asdadasd",
"type": "post",
"slug": "asdasdasda",
"featured_images": {
"images": {
"300": "/uploads/post_images/2019/300_1573573846.png",
"600": "/uploads/post_images/2019/600_1573573846.png",
"900": "/uploads/post_images/2019/900_1573573846.png",
"original": "/uploads/post_images/2019/1573573846.png"
},
"thumbnail": "/uploads/post_images/2019/300_1573573846.png"
},
"lang": "fa",
"visit": 0,
"categories": [
{
"id": 2,
"title": "bbbbbbbb",
"lang": "fa",
"parent": 0,
"pivot": {
"contents_id": 2,
"content_categories_id": 2
}
}
]
}
]
problem is on this line of code:
json.decode(response.body)
Try this:
list = List<KeywordsResponse>.from(response.body.map((x) => KeywordsResponse.fromJson(x)));
Related
Getting this type of response when run API:
[{
"docId": 1053,
"tokenNo": 23477779999999,
"docTitle": "Karishma resort ,baner",
"address": "baner",
"city": "pune",
"partyName": "Rajesh patil",
"pinCode": "452899",
"docType": "Commercial",
"duration": "24",
"startDate": "2023-01-11",
"endDate": "2025-01-10",
"docStatus": "Open",
"rentDesc": "17000",
"createdBy": "Vaishnavi",
"updatedBy": "null"
}, {
"docId": 1052,
"tokenNo": 22010799911122,
"docTitle": "swapnapurti heights",
"address": "Pirangut",
"city": "Pune",
"partyName": "Pranjali Sul",
"pinCode": "411033",
"docType": "Residential",
"duration": "12",
"startDate": "2023-01-07",
"endDate": "2024-01-06",
"docStatus": "Open",
"rentDesc": "",
"createdBy": "",
"updatedBy": ""
}, {
"docId": 1050,
"tokenNo": 72389572857572,
"docTitle": "Krishna Murti Nivas",
"address": "Bavdhan",
"city": "pune",
"partyName": "Suhas kale",
"pinCode": "736476",
"docType": "Residential",
"duration": "24",
"startDate": "2023-01-14",
"endDate": "2025-01-13",
"docStatus": "Open",
"rentDesc": "87033",
"createdBy": "null",
"updatedBy": "null"
}, {
"docId": 932,
"tokenNo": 2212010909755,
"docTitle": "6/10 B Digital Apartment",
"address": "Kothrud",
"city": "Pune",
"partyName": "Suresh",
"pinCode": "411112",
"docType": "Residential",
"duration": "11",
"startDate": "2022-12-01",
"endDate": "2023-12-01",
"docStatus": "Open",
"rentDesc": "5000",
"createdBy": "Swati",
"updatedBy": null
}]
I have implemented below method to get documents which contains docStatus:"Open" only:
List<Document> docs = [];
openedDocs() async {
final docs = await DocumentController.getdocs(value);
List<Document> opened;
for (int i = 0; i <= docs.length; i++) {
docs[i].docStatus == "Open" ? this.docs = docs : this.docs = List.empty();
}
}
Method getDocs() is like below:
static Future<List<Document>> getdocs(String query) async {
await SharedPrefService.init();
var AuthToken = SharedPrefService.pref.getString('authToken');
// final url = Uri.parse('http://192.168.0.131 :8080/Atdochub-3/document/');
final url = Uri.parse(
// 'http://192.168.0.131:8080/AtdochubJ-3/document/'
'http://192.168.0.131:8080/AtdochubJ-3/document/');
final response = await http.get(url, headers: {
HttpHeaders.authorizationHeader: '${AuthToken}',
'Content-Type': 'application/json; charset=UTF-8',
});
if (response.statusCode == 200) {
final List docs = json.decode(response.body);
// return json.decode(response.body).toList();
return docs.map((json) => Document.fromJson(json)).where((doc) {
final titleLower = doc.docTitle.toLowerCase();
final tokenLower = doc.tokenNo.toString();
final searchLower = query.toLowerCase();
return titleLower.contains(searchLower) ||
tokenLower.contains(searchLower);
}).toList();
} else {
throw Exception();
}
}
I just wants to get list of all documents which have docStatus="Open"
Use where to create a matching criteria
return docs.map((json) => Document.fromJson(json))
.where((doc) => doc.docStatus == 'Open').toList();
For my Calendar i get the following data as JSON from the Backend (*JAVA-Type = Map<LocalDate, List<Event>>):
{
"2022-05-28": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
}
],
"2022-05-27": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
},
{
"id": 1,
"title": "Testevent",
"fromDate": "2022-05-27T11:21:04.573754",
"toDate": "2022-05-27T12:21:04.573754",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "normal"
}
],
}
My Event Class looks like:
Class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
}
Now i need the same structure i had in the Backend (Map<DateTime, <List<Event>>) for my Calendar widget and i have no real clue on how to do it. I know how to convert json data into an object if i get a list of an object, but how can i store the date as key of the resulting map?
My code by now:
Future<Map<DateTime, List<Event>>> getEvents(DateTime _fromDate, DateTime
_endDate) async {
String _from = _fromDate.toString().split('.').first;
String _end = _endDate.toString().split('.').first;
final response = await get('${_url}calendar/events/$_from/$_end',
headers: {HttpHeaders.authorizationHeader: 'Bearer $_bearer'});
if (response.status.hasError) {
return Future.error('${response.statusText}');
} else {
final parsed = jsonDecode(response.body);
return parsed;
}
}
You need to do something like that:
var json = {...}; // <-- json obj
// method to parse data to map with list Event
dynamic fromJson(Map<String, dynamic> json){
var map = new Map();
json.keys.forEach((key){
// key is the date
map[key] = json[key].map((e) => Event.fromJson(e)).toList(); // <- need to create a method fromJson in your Event class
});
return map;
}
(...)
class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
fromJson(Map<String, dynamic> json) => Event(...); // <- parse json to Event class
}
I'm trying to get json data from Api by using the following
Future<SubjectList> getsubjectList(
String userId, String accountId) async {
final response = await http
.get(Uri.https(_baseUrl, 'v1/package/subject-details'), headers: {
'Content-Type': 'application/json',
'user-id': userId,
'account-id': accountId,
});
SubjectList jsonresponse = json.decode(response.body); //'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'SubjectList'
print('This is response =$jsonresponse');
return jsonresponse;
}
I have modelled the object as follows
class SubjectList {
SubjectList({
this.subject,
this.score,
this.progress,
});
String? subject;
double? score;
String? progress;
factory SubjectList.fromMap(Map<String, dynamic> json) => SubjectList(
subject: json["subject"],
score: json["score"].toDouble(),
progress: json["progress"],
);
Map<String, dynamic> toJson() => {
"subject": subject,
"score": score,
"progress": progress,
};
}
The Data is as follows
{
"success": true,
"data": [
{
"subject": "Grammar",
"score": 57.17,
"progress": "96.77%"
},
{
"subject": "Maths",
"score": 52.12,
"progress": "73.08%"
},
{
"subject": "EVS",
"score": 55.75,
"progress": "97.96%"
},
{
"subject": "Social Studies",
"score": -1,
"progress": "-1%"
},
{
"subject": "Hindi",
"score": 51.36,
"progress": "60.87%"
},
{
"subject": "Vocabulary",
"score": 62.55,
"progress": "68.12%"
},
]
When ever i try to access using the model i'm receiving the error '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'SubjectList'. How do I get the data properly ?
Change this line
SubjectList jsonresponse = json.decode(response.body);
to something like
List<SubjectList> list = json.decode(response.body)['data'].map((d) => SubjectList.fromMap()).toList();
You can create a class for the response itself and the do the fromMap on it.
I am new to flutter . i am trying to fetch responnse from api . i am getting response as 200 but unable to retreive particular object inside it .
please have a look at a model class below and suggest me what wrong i am doing
class Response {
bool success;
List<dynamic> errors;
List<CourseParent> courses;
Batches coursedetail;
Response({this.success,this.errors,this.courses,this.coursedetail});
factory Response.fromJson(Map<String, dynamic> map) {
return Response(
errors: map['errors'],
success: map['success'],
courses: map['courses'] != null
? map['courses'].map<CourseParent>((json) => CourseParent.fromJson(json)).toList()
: null,
coursedetail: map['courseDetails'] != null
? map['courseDetails'].map<Batches>((json) => Batches.fromJson(json))
: null,
);
}
Map<String, dynamic> toJson() {
return {"success": success, "errors": errors, "courses": courses, "courseDetails" : coursedetail};
}
#override
String toString() {
return 'Response{ success: $success, errors: $errors , courses: $courses, courseDetails: $coursedetail }';
}
}
List<Response> profileFromJson(String jsonData) {
final data = json.decode(jsonData);
return List<Response>.from(data.map((item) => Response.fromJson(item)));
}
Response responseFromJson(String str) {
final jsonData = json.decode(str);
print("##-response"+jsonData.toString());
return Response.fromJson(jsonData);
}
String responseToJson(Response data) {
final jsonData = data.toJson();
print("##--encoding"+json.encode(jsonData));
return json.encode(jsonData);
}
i am getting the error as below
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Acutall expected json is below
{
"success": true,
"courseDetails": {
"courseId": 34,
"title": "Taxi Drivers Qualification Program",
"code": "TX001",
"image": "uploads\\9e5dba0e-0e25-4247-a3fa-a2a404aadacd.jpg",
"target": 0,
"batches": [
{
"batchId": 41,
"courseId": 34,
"instructorId": 22,
"venueId": 1,
"startDate": "2021-01-03T00:00:00",
"endDate": "2021-01-17T00:00:00",
"startTime": "2021-01-03T09:17:00",
"endTime": "2021-01-03T12:17:00",
"capacity": 25,
"gender": 2,
"instructor": [
{
"instructorId": 22,
"civilId": "931285",
"forceId": "123",
"title": 15,
"fullname": "Mansoor Abdulrahim Al Rasbi",
"email": "steve.jobs#apple.com",
"mobile": "99699633",
"type": 1
}
],
"venue": [
{
"venueId": 1,
"name": "B22",
"branchId": 1,
"branch": [
{
"branchId": 1,
"name": "Head Quarters - Muscat",
"capacityTheoretical": 175,
"capacityPractical": 125
}
],
"bookingFees": 25
},
{
"venueId": 21,
"name": "Meetings Hall",
"branchId": 1,
"branch": [
{
"branchId": 1,
"name": "Head Quarters - Muscat",
"capacityTheoretical": 175,
"capacityPractical": 125
}
],
"bookingFees": 20
},
{
"venueId": 41,
"name": "Store Muscat Branch",
"branchId": 1,
"branch": [
{
"branchId": 1,
"name": "Head Quarters - Muscat",
"capacityTheoretical": 175,
"capacityPractical": 125
}
]
}
]
}
]
}
}
You need to parse courseDetails directly, it is an object, not Map or List:
coursedetail: map['courseDetails'] != null ? Batches.fromJson(map['courseDetails']) : null;
I spent days to think&googled about how to achieve this, but still can't get any idea how it actually works...
I would appreciate if someone could give me some advise or point me to the right direction.
So in my case, I will fetch a json list from an APIs, and I just wanna store the Shop class into a list which will build in a listView.
Here's my code sample.
Widget buildShopList() {
return ListView.builder(
itemCount: shopList.length,
padding: const EdgeInsets.only(top: 8, bottom: 110),
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
final int count = shopList.length > 10 ? 10 : shopList.length;
return ShopListView(
callback: () {},
shop: shopList[index],
);
},
);
}
class ShopListView extends StatelessWidget {
const ShopListView({Key key, this.shop}: super(key: key);
final Shop shop;
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(shop.type.name),
Text(shop.name),
]
);
}
}
Shop model class
class Shop {
String name;
String website;
String email;
ShopType type;
Shop({this.name, this.website, this.email, this.type});
factory Shop.fromJson(Map<String, dynamic> json) => Shop(
name: json["name"],
type: json["shop_types"],
// can't figure out how to pass the shop type model class into here
website: json["website"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"name": name,
"shop_types": type,
"website": website,
"email": email
};
}
ShopType model class
class ShopType {
int id;
String name;
String description;
ShopType({this.id, this.name, this.description});
factory ShopType.fromJson(Map<String, dynamic> json) => ShopType(
id: json["id"],
name: json["name"],
description: json["description"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
};
}
Here's the json will response from APIs
{
"success": true,
"data": {
"shops": [
{
"id": 1,
"name": "shop name a",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
"pivot": {
"shop_id": 1,
"shop_type_id": 1
}
}
]
},
{
"id": 2,
"name": "shop name b",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 2,
"name": "Store",
"description": "Store",
"pivot": {
"shop_id": 2,
"shop_type_id": 2
}
}
]
},
{
"id": 3,
"name": "shop name c",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
"pivot": {
"shop_id": 3,
"shop_type_id": 1
}
},
{
"id": 2,
"name": "Type B",
"description": "Type B",
"pivot": {
"shop_id": 3,
"shop_type_id": 2
}
}
]
}
],
"shopTypes": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
},
{
"id": 2,
"name": "Type B",
"description": "Type B",
}
]
}
}
Fetch data From network with Dio
fetchShopsAndSaveLocal() async{
var dio = Dio();
dio.options.connectTimeout = 4500 * 10; //45s
dio.options.receiveTimeout = 4500 * 10;
try {
var param = {
"useremail": "dpk.7#gmail.com"
, "password": "123456"};
var response = await dio.post(
"https://api.test/getstores", data: FormData.fromMap(param));
var json = jsonDecode(response.data);
ModelStore store = ModelStore.fromJson(json);
List<Shops> shops = store.shops;
for (var shop in shops) {
saveEverySingleShopInDatabase(shop);
}
} catch (e) {}
}
After that use SQFlite
To Save shops data in Database, after saving data in the local database, fetch data to listview every time from the database.