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;
Related
Given the following map:
"user":
{
"userid":0,
},
"appData":{
"title":"Test",
"pages":1,
"posts":[
{
"postid":27979530,
"text":Test,
},
{
"postid":7732445,
"text":Test123,
},
{
"postid":9463254,
"text":Test568,
},
]
}
Given that map I want to try to find the entry for postid 7732445 so I can return the text value of Test123
What is the best way of doing something like that?
Given that
final Map<String, dynamic> json = {
"user": {
"userid": 0,
},
"appData": {
"title": "Test",
"pages": 1,
"posts": [
{
"postid": 27979530,
"text": "Test",
},
{
"postid": 7732445,
"text": "Test123",
},
{
"postid": 9463254,
"text": "Test568",
},
]
}
};
you could do this search by doing
json["appData"]["posts"]
.firstWhere(
(item) => item["postid"] == 7732445,
orElse: () => <String, Object>{},
)["text"]
Because of the orElse, this will return null if not found.
I have a map, with multiple layers, some of the layers have an events field which may contain 0 or more event listings inside of it.
Some of events are nested deeper into the map, while others are closer to the top layer.
Here is what the graphql query result looks like:
{
"data": {
"users": [
{
"id": 16,
"friends": [
{
"senderId": 16,
"receiverId": 17,
"userByReceiverid": {
"id": 17,
"events": [],
"friends": [
{
"receiverId": 14,
"userByReceiverid": {
"id": 14,
"events": [
{
"id": 3,
"photoUrl": "none",
"name": "hello",
"date": "1982-06-27",
"startTime": "01:00:00+00",
"endTime": "02:00:00+00",
"fee": "$2.00",
"maxNumber": 10,
"ageRestriction": "none",
"about": "amazing",
"allowShare": false,
"private": false,
"timestamp": "2021-06-26T17:57:13.224383+00:00",
"senderId": 14
}
]
}
},
{
"receiverId": 20,
"userByReceiverid": {
"id": 20,
"events": []
}
}
]
}
}
],
"friendsByReceiverid": [
{
"senderId": 20,
"receiverId": 16,
"user": {
"id": 20,
"events": [],
"friendsByReceiverid": [
{
"receiverId": 20,
"user": {
"id": 14,
"events": [
{
"id": 3,
"photoUrl": "none",
"name": "hello",
"date": "1982-06-27",
"startTime": "01:00:00+00",
"endTime": "02:00:00+00",
"fee": "$2.00",
"maxNumber": 10,
"ageRestriction": "none",
"about": "amazing",
"allowShare": false,
"private": false,
"timestamp": "2021-06-26T17:57:13.224383+00:00",
"senderId": 14
}
]
}
},
{
"receiverId": 20,
"user": {
"id": 17,
"events": []
}
}
]
}
}
]
}
]
}
}
I want to search the Map and make a list that contains all the events that are unique, so no duplicates if possible.
How would I go about pulling out only the events field from a map at any given point?
Essentially what you need is a function (visitObject) that goes through each key of the a Map and recursively calls itself till all properties have been checked.
The function should also check for the possible types it can operate on and handle the data so you can call the visitObject function with the right arguments.
I believe the right data structure here would be a Set. In dart as Set is defined as A collection of objects in which each object can occur only once.
However Set a set falls back to the dart method of equality which is the == operator, so you would either need to use a calls for Events or use a package like BuiltValue which will generate the == operator for your value types.
Here is an example that can help you get started, I have left equality checking for you to determine what best and how you want to apply it.
final Set<Map<String, dynamic>> items = {};
void main() {
visitObject(data);
}
void visitObject(object) {
if (object is List) {
for(dynamic item in object) {
visitObject(item);
}
} else if (object is Map) {
if (object.containsKey('events')) {
var _events = object['events'];
if (_events is List && _events.isNotEmpty) {
_events.forEach((e) {
if (!items.contains(e)) {
items.add(e);
}
});
}
}
for (dynamic item in object.values) {
visitObject(item);
}
}
}
Additional Reading for equality:
==Operator
hashCode
BuiltValue
Currently I am getting this kind of issue from my code. I was trying to solved this problem continuously. But could not fund the solution of this problem.
Json Codes
{
"id": 22,
"client_need_id": 46,
"clientNeed": {
"id": 46,
"client_id": 29,
"perpose": "Pooja",
"details": "Test",
"when": "2020-08-28 20:11",
"for": null,
"accepted_by": 10,
"name": "Sfgdsa",
"mobile": "567896789",
"email": "sdnsd#asd.com",
"org_name": "Buii",
"address": "Tata",
"city": "Kolkata",
"state": "West Bengal",
"pincode": "789009",
"country": "India",
"latitude": null,
"longitude": null,
"client_ip": null,
"device": null,
"created_at": "2020-08-23T14:40:06.000000Z",
"updated_at": "2020-09-02T18:07:40.000000Z"
},
"quote_details": null,
"quote_amount": null,
"isCalled": 0,
"isChecked": 0,
"isAccept": 1,
"isGoing": 0,
"checkIn": "2020-09-03 02:00:00",
"checkOut": "2020-09-03 02:00:15",
"pandit_id": 10,
"pandit": {
"id": 10,
"name": "Ajay Roy",
"mobile": "8013138886",
"sms_token": null,
"mobile_verified_at": null,
"email": "ajay#abc.com",
"email_token": null,
"email_verified_at": null,
"password": "5f4dcc3b5aa765d61d8327deb882cf99",
"remember_token": null,
"avatar": null,
"address": "dum dum cantonment",
"city": "Kolkata",
"state": "West Bengal",
"country": "India",
"pincode": 700028,
"location_id": null,
"travelled": null,
"adharcard": "34567890",
"pancard": "ATD8994568",
"specialisation": "Vastushastri",
"services": [
"Artrology",
"Numerology"
],
"min_charge": "500",
"max_charge": "1000",
"online_charge": "700",
"qualification": "Test1",
"experience": "12 Years",
"language": "Bengali",
"active": "0",
"varify": "1",
"payment_mode": "{\"bank_name\":\"HDFC Bank\",\"bank_address\":\"Dum Dum Cant\",\"ifsc_code\":\"HDFC098765\",\"account_no\":\"987654654678\",\"account_holder\":\"Abit Roy\"}",
"created_at": "2020-08-31T19:03:56.000000Z",
"updated_at": "2020-09-16T12:40:54.000000Z"
},
"visits": [
{
"id": 70,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": "2020-09-03 02:00:00",
"checkOut": null,
"created_at": "2020-09-02T20:30:00.000000Z",
"updated_at": "2020-09-02T20:30:00.000000Z"
},
{
"id": 71,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": null,
"checkOut": "2020-09-03 02:00:15",
"created_at": "2020-09-02T20:30:15.000000Z",
"updated_at": "2020-09-02T20:30:15.000000Z"
}
]
}
Lead Model
import 'dart:convert';
import 'package:PandeetApp/models/client_need.dart';
import 'package:PandeetApp/models/pandit.dart';
import 'package:PandeetApp/models/visit.dart';
import 'package:PandeetApp/services/lead.dart';
class Lead extends LeadService {
int id;
int clientNeedId;
ClientNeed clientNeed;
String quoteDetails;
String quoteAmount;
int isCalled;
int isChecked;
int isAccept;
int isGoing;
String checkIn;
String checkOut;
int panditId;
Pandit pandit;
List<Visit> visits;
Lead({
this.id,
this.clientNeedId,
this.clientNeed,
this.quoteDetails,
this.quoteAmount,
this.isCalled,
this.isChecked,
this.isAccept,
this.isGoing,
this.checkIn,
this.checkOut,
this.panditId,
this.pandit,
this.visits,
});
Future<List<Lead>> fetchLeads() async {
var datas = await super.fetchDatas();
var dataList = json.decode(datas);
var leads = dataList.map((e) => Lead.fromJson(e)).toList();
return leads;
}
factory Lead.fromJson(Map<String, dynamic> json) {
List<Visit> visits = List<Visit>();
if (json['visits'] != null) {
json['visits'].forEach((v) {
visits.add(Visit.fromJson(v));
});
}
return Lead(
id: json['id'],
clientNeedId: json['client_need_id'],
clientNeed: json['clientNeed'] != null
? ClientNeed.fromJson(json['clientNeed'])
: ClientNeed(),
quoteDetails: json['quote_details'],
quoteAmount: json['quote_amount'],
isCalled: json['isCalled'],
isChecked: json['isChecked'],
isAccept: json['isAccept'],
isGoing: json['isGoing'],
checkIn: json['checkIn'],
checkOut: json['checkOut'],
panditId: json['pandit_id'],
pandit:
json['pandit'] != null ? Pandit.fromJson(json['pandit']) : Pandit(),
visits: visits,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
if (this.clientNeed != null) {
data['clientNeed'] = this.clientNeed.toJson();
}
data['quote_details'] = this.quoteDetails;
data['quote_amount'] = this.quoteAmount;
data['isCalled'] = this.isCalled;
data['isChecked'] = this.isChecked;
data['isAccept'] = this.isAccept;
data['isGoing'] = this.isGoing;
data['checkIn'] = this.checkIn;
data['checkOut'] = this.checkOut;
if (this.pandit != null) {
data['pandit'] = this.pandit.toJson();
}
if (this.visits != null) {
data['visits'] = this.visits.map((v) => v.toJson()).toList();
}
return data;
}
}
Screen Part
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List leads = snapshot.data;
// print(leads.length); // Data Not Getting Here
if (leads.length > 0) {
return dataList(leads);
} else {
return Container(
padding: EdgeInsets.only(top: 200),
child: Text("You have no clients"),
);
}
} else if (snapshot.hasError) {
print(snapshot.error);
return Text("Server is Down now. Try again later");
}
return Container(
padding: EdgeInsets.only(top: 200),
child: CircularProgressIndicator(
backgroundColor: Colors.redAccent,
),
);
},
);
I think here have the problem. I was completed my project but this type of problem ruin my project. I could not understand where i am wrong for this problem. Exact line number could not found. Give just hint but where exactly problem not understandable. Please help me as soon as possible.
Don't cast the snapshot data as List instead use var. Try the print results before error and proceed further
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var leads = snapshot.data; // use var instead of List
// try this in your case it is received as String
print(leads.runtimeType.toString())
// if it is string convert to List.
var leadsJson = jsonDecode(leads)
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.
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)));