Factory Unhandled Exception: type '(dynamic) => DataAd' is not a subtype of type '(String, dynamic) - flutter

I have trying to figure out in some question but there is no case like me. I am getting the code from tutorial and I have understand it. However, the problem is in the tutorial. It uses static JSON (list) where mine using dynamic which contain keys.
Here is my code
class CompileAd {
String status;
String notification;
Map<int,DataAd> adData;
CompileAd({
required this.status,
required this.notification,
required this.adData,
});
factory CompileAd.fromJson(Map<String, dynamic> json) => CompileAd(
status: json["status"],
notification: json["notification"],
adData: Map<int,DataAd>.from(
json["adData"].map((x) => DataAd.fromJson(x))), => ERROR HERE
);
Map<String, dynamic> toJson() => {
"status": status,
"notification": notification,
"adData": Map<dynamic,dynamic>.from(adData.map((key,x) => x.toJson())), => HERE ALSO (Actually, I wish to use "jsonEncode(adData)" since its working but no idea which one better)
};
}
Error Log
lib/class/adClass.dart:27:69: Error: A value of type 'Map<String,
dynamic>' can't be returned from a function with return type
'MapEntry<dynamic, dynamic>'.
'Map' is from 'dart:core'.
'MapEntry' is from 'dart:core'.
"adData": Map<dynamic,dynamic>.from(adData.map((key,x) => x.toJson())),
^
Here is the json object
adData => (keyID,adObject)
{
"adData": {
"77289": {
"id": 77289,
"username": "magdatjahja#gmail.com",
"category": "rumah",
"subCategory": "rumah",
"type": "dijual",
"uniqueId": "6436",
"title": "Jual Rumah di Mazenta Bintaro Tangerang Selatan",
"slug": "jual-rumah-di-mazenta-bintaro-tangerang-selatan",
"content": "Jual rumah di mazento bintaro tangerang selatan\r\n\r\nSatu-satunya hunian premium di kawasan Bintaro bernuansa Japan Ambiance Living :\r\n\r\nType unit :\r\n\ud83d\udc49 Type 6 \r\nLuas Tanah: 72m2 \r\nLuas Bangunan: 83m2 \r\nKamar Tidur: 3 \r\nKamar Mandi: 2 \r\n\r\n\ud83c\udf81Dapatkan Promo Early Bird Price !!!\ud83c\udf81\r\n\u2705HARGA MULAI RP.1,8 M\r\n\u27053 unit AC 1 Pk\r\n\u2705Free Mini Canopy\r\n\u2705 Lucky Bowl up to Iphone13\r\n\u2705 SmartDoorlock\r\n\r\nLokasi\r\n\ud83d\ude97 Hanya 3 menit ke BXchange Mall Bintaro!\r\n\ud83d\ude97 Hanya 2-3 menit ke pintu tol! dan jumlah unit SANGAT terbatas!\r\n\ud83d\ude97Hanya 3 Menit Statiun Jurang Mangu\r\n\ud83d\ude97Hanya 3 menit UPJ University\r\n\r\n\r\nHubungi AGENT MERKETING\r\nMagda 08118897878",
"bid": 2000,
"balance": 1,
"price": "1800000000",
"province": "banten",
"regency": "tangerang selatan",
"district": "",
"village": "",
"complex": "",
"rd": 1,
"premier": "2022-03-22 11:33:13",
"partner": 1,
"privateSync": "0000-00-00 00:00:00",
"penaltyTime": null,
"data": {
"price": {
"price": "1800000000"
},
"priceUnit": "",
"province": "banten",
"regency": "tangerang selatan",
"district": "",
"village": "",
"additional": {
"address": "Bintaro, Tangerang Selatan",
"complex": "",
"lt": "72",
"lb": "83",
"bedroom": "3",
"bathroom": "2",
"maidbedroom": "",
"maidbathroom": "",
"floor": "",
"garage": "",
"carports": "",
"electricity": "",
"orientation": "",
"interior": ""
},
"facebook": "2022-03-22 14:54:05",
"twitter": "0000-00-00 00:00:00",
"pinterest": "0000-00-00 00:00:00",
"tumblr": "0000-00-00 00:00:00",
"premier": "2022-03-22 11:33:13",
"partner": true,
"penaltyTime": "2022-03-22 11:32:01",
"instagram": "2022-03-22 14:47:14"
},
"images": {
"images": ["jual-rumah-di-mazenta-bintaro-tangerang-selatan-0XOV3B.jpg", "jual-rumah-di-mazenta-bintaro-tangerang-selatan-VS38QN.jpg", "jual-rumah-di-mazenta-bintaro-tangerang-selatan-14RHI3.jpg"],
"imagesAdditional": [],
"images360": []
},
"video": {
"1": "https:\/\/youtu.be\/CA6iNWEDa1E"
},
"sosmed": 0,
"view": 28,
"contact": 0,
"status": "active",
"checked": 1,
"sold": "0000-00-00 00:00:00",
"modify": "0000-00-00 00:00:00",
"waktu": "2022-03-21 17:40:03",
"dir": "\/uploads\/images\/2022\/03\/77289\/",
"url": "\/properti\/tangerang-selatan\/6436-jual-rumah-di-mazenta-bintaro-tangerang-selatan\/"
}
},
"status": "success",
"notification": "Berhasil memproses permintaan"
}
I really appreciate any answers. Thank you.

Related

Uncaught Error: TypeError: null: type 'JSNull' is not a subtype of type 'List<dynamic>'

I'm looking for a way to copy the values in the category_name field to a list without using the add operator. The idea behind not using the add operator is to prevent the existing data from remaining in the list. For example, if in a newer JSON data set, the values in category_name are [xyz, food] & [efg, food], then I intend to print [xyz, efg] instead of [Veg, Veg, NonVeg, XYZ, efg].
Please note that the JSON data currently assigned to duplicates is meant to be dynamic which is why it is important for me to find a solution in which I can only assign the values in category_name from the current JSON data set which is meant to change with API calls.
void main() {
List<dynamic> list = [];
Map<String, dynamic> duplicates = {
"status": "success",
"data": [
{
"product_id": 17,
"category_name": [
"Veg",
"Dinner"
],
"restaurant_name": "Mocambo",
"product_name": "Panner Makhani",
"product_description": "Mouth Smacking Creamy Indian Gravy.",
"product_image": "/assets/product/WOw4Rc03-02-08.jpg",
"product_selling_price": "240",
"product_status": "active",
"product_quantity": "50",
"product_rating": "",
"product_rating_count": "",
"product_sell_count": "0"
},
{
"product_id": 16,
"category_name": [
"Veg",
"Dinner"
],
"restaurant_name": "Mocambo",
"product_name": "Panner Makhani",
"product_description": "Mouth Smacking Creamy Indian Gravy.",
"product_image": "/assets/product/WOw4Rc03-02-08.jpg",
"product_selling_price": "240",
"product_status": "active",
"product_quantity": "50",
"product_rating": "",
"product_rating_count": "",
"product_sell_count": "0"
},
{
"product_id": 15,
"category_name": [
"NonVeg",
"Snacks"
],
"restaurant_name": "Mocambo",
"product_name": "Cheese Steak Burger",
"product_description": "Tasty steak burger oozing with the goodness of creamy cheese",
"product_image": "/assets/product/SBuZnx02-54-20.jpg",
"product_selling_price": "150",
"product_status": "active",
"product_quantity": "20",
"product_rating": "",
"product_rating_count": "",
"product_sell_count": "0"
}
]
};
list = duplicates['data'].forEach((value) => value["category_name"][0]);
print(list);
}
I tried doing list = duplicates['data'].forEach((value) => value["category_name"][0]); thinking that everytime the JSON data in duplicates changes, the previous values will get overwritten with new ones. But it doesn't really work that way because of the above error. Any help will be appreciated.

Fliter JSON Map Data using ID in Flutter

I'm struggling to understand how I can filter data by ID using providers. The approach I have tried yields the below error:
Class '_InternalLinkedHashMap<String, Object>' has no instance getter 'id'.
Receiver: _LinkedHashMap len:8
Tried calling: id
Given my little experience in Flutter, any help or suggestion would be highly appreciated.
The code I have written is below:
class PopularDishesProvider with ChangeNotifier {
final Map<String, dynamic> _popularDishes = { //This is the JSON map that I would like to filter from
"data": [
{
"id": "1",
"name": "Chicken Tandoor Combo",
"restaurantName": "Tandoori House",
"price": "455",
"rating": "4.3",
"totalRatings": "154",
"image": "assets/images/Rectangle 17323.png",
"isFavourite": false
},
{
"id": "2",
"name": "Pan Cake",
"restaurantName": "The Pancake Centre",
"price": "250",
"rating": "4.7",
"totalRatings": "256",
"image": "assets/images/Rectangle 17324.png",
"isFavourite": false
},
{
"id": "3",
"name": "Salad",
"restaurantName": "The Pancake House",
"price": "180",
"rating": "4.1",
"totalRatings": "203",
"image": "assets/images/Rectangle 17325.png",
"isFavourite": false
},
{
"id": "4",
"name": "Roast Chicken",
"restaurantName": "Kentucky\"s Fried Chicken",
"price": "550",
"rating": "4.8",
"totalRatings": "1000",
"image": "assets/images/Rectangle 17323 (2).png",
"isFavourite": false
},
{
"id": "5",
"name": "Ice Cream",
"restaurantName": "Naturals",
"price": "80",
"rating": "5.0",
"totalRatings": "1500",
"image": "assets/images/Rectangle 17324 (2).png",
"isFavourite": false
},
{
"id": "6",
"name": "Chicken Tandoor Combo",
"restaurantName": "Tandoori House",
"price": "455",
"rating": "4.3",
"totalRatings": "154",
"image": "assets/images/Rectangle 17323.png",
"isFavourite": false
},
{
"id": "7",
"name": "Pan Cake",
"restaurantName": "The Pancake Centre",
"price": "250",
"rating": "4.7",
"totalRatings": "256",
"image": "assets/images/Rectangle 17324.png",
"isFavourite": false
},
{
"id": "8",
"name": "Salad",
"restaurantName": "The Pancake House",
"price": "180",
"rating": "4.1",
"totalRatings": "203",
"image": "assets/images/Rectangle 17325.png",
"isFavourite": false
},
{
"id": "9",
"name": "Roast Chicken",
"restaurantName": "Kentucky\"s Fried Chicken",
"price": "550",
"rating": "4.8",
"totalRatings": "1000",
"image": "assets/images/Rectangle 17323 (2).png",
"isFavourite": false
},
{
"id": "10",
"name": "Ice Cream",
"restaurantName": "Naturals",
"price": "80",
"rating": "5.0",
"totalRatings": "1500",
"image": "assets/images/Rectangle 17324 (2).png",
"isFavourite": false
}
]
};
Map<String, dynamic> get popularDishes {
return {..._popularDishes};
}
Map<String, dynamic> getProductById(String id) { //The filter method that I've tried to write that yields the error
return _popularDishes["data"].where((value) => value.id == id).toList();
}
This is how I'm calling the getProductById method using provider.
routes['id'] is basically the id taken as a route argument from the previous page. The id is derived from the same JSON data that is on this question.
class CartScreenState extends State<CartScreen> {
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
final textScale = MediaQuery.of(context).textScaleFactor * 1.2;
final routes =
ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
routes['id']
final id = routes['id'];
final provider =
Provider.of<PopularDishesProvider>(context).getProductById(id);
Map<String, dynamic> getProductById(String id) { //The filter method that I've tried to write that yields the error
return _popularDishes["data"].where((value) => value.id == id).toList();
}
First of all, you are accessing id as a getter on the map object so you have to write it like this
return _popularDishes["data"].where((value) => value['id'] == id).toList();
The second thing is your function return type is Map<String, dynamic> but you are returning list as you have used toList() so either make your function return type as List<Map<String, dynamic>> or if you have to return only first single match then you can use firstWhere instead of where
A possible solution could be the following:
import 'package:collection/collection.dart';
Map<String, dynamic>? getProductById(String id) {
final dishes = _popularDishes["data"] as List<Map<String, dynamic>>;
return dishes.where((dish) => dish["id"] == id).firstOrNull;
}
By type casting your dishes list, you can make clear that you are dealing with maps of a certain type (like Map<String, dynamic>). That way you can access a certain value by its key using square brackets (dish["id"]) and then compare the value to the passed parameter.
Additionally, you tried to return a list (by using the toList() method) but your return type was Map<String, dynamic>. So if you would like to return a list, you could change the return type to List<Map<String, dynamic>>. Otherwise you can use firstOrNull (from the collection package) to get your result (or null if nothing was found). For returning null, you must mark the return type nullable.
Hope this solves the problem :)

unable to retrieve object inside object

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;

POST request with webmethods

i am using webmethods platform 10.1 and i developed a service that is supposed to receive data as Post request.
when i try to run it on IDE it works fine, but when i publish it and try to access it through API Portal, it does not work.
i am not sure how to map my JSON to my Document. Can anyone please guide me in this regard?
I have attached my Document screen shot as well as the json i am trying to Post.
Can anyone explain how both are not related, because when i post the below JSON to my service, i do not get the values.
{
"EventCompanyId": "443",
"PositionTitleEn": "New post",
"PositionTitleAr": "New post",
"ReportsTo": "Manager",
"KnowledgeRequiredEn": "Basic knowlege",
"KnowledgeRequiredAr": "Basic knowledge",
"ExperienceRequired": "7 years",
"Gender": "1",
"EducationLevel": "4",
"CreatedBy": "1",
"UpdatedBy": "1",
"StartSalary": "35000",
"EndSalary": "35000",
"Status": "0",
"Certificate": "BS",
"YearsOfExperience": "7",
"Major": "5",
"Age": "30",
"JobType": "1",
"TrainingCourse": "",
"Weekdays": "",
"WorkingHours": "",
"Language": "1",
"Shift": "",
"JobLocations": [
{
"EmiratesId": 3,
"NumberOfVacancies": 3,
"EmiratesArea": "United Arab Emirates",
"Latitude": ,
"Longitude": ,
"EmirateEn": null,
"EmirateAr": null,
"EmirateName": null
},
{
"EmiratesId": 6,
"NumberOfVacancies": 23,
"EmiratesArea": " Dubai - United Arab Emirates",
"Latitude": 25.20447520001559,
"Longitude": 55.28122901916504,
"EmirateEn": null,
"EmirateAr": null,
"EmirateName": null
},
{
"EmiratesId": 1,
"NumberOfVacancies": 5,
"EmiratesArea": "Dubai - United Arab Emirates",
"Latitude": ,
"Longitude": ,
"EmirateEn": null,
"EmirateAr": null,
"EmirateName": null
},
{
"EmiratesId": 2,
"NumberOfVacancies": 3,
"EmiratesArea": "D72 - Dubai - United Arab Emirates",
"Latitude": ,
"Longitude": ,
"EmirateEn": null,
"EmirateAr": null,
"EmirateName": null
}
]
}
i have found a solution for it, the problem was i needed to remove Job Properties from under Job Document, they should not be inside any other property.

GET request endpoint results rider_id is null

why is it that the riders have a null rider_id in the example? but the description says otherwise? riders[].rider_id : The hashed rider uuid. It doesnt say anything about it being may be null. Else what's the point of returning it. GET request
or is just an example, and the actual response has all of these ids not null
{
"product_id": "17cb78a7-b672-4d34-a288-a6c6e44d5315",
"request_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
"status": "accepted",
"surge_multiplier": 1.0,
"shared": true,
"driver": {
"phone_number": "(555)555-5555",
"sms_number": "(555)555-5555",
"rating": 5,
"picture_url": "https:\/\/d1w2poirtb3as9.cloudfront.net\/img.jpeg",
"name": "Bob"
},
"vehicle": {
"make": "Bugatti",
"model": "Veyron",
"license_plate": "I<3Uber",
"picture_url": "https:\/\/d1w2poirtb3as9.cloudfront.net\/car.jpeg"
},
"location": {
"latitude": 37.3382129093,
"longitude": -121.8863287568,
"bearing": 328
},
"pickup": {
"latitude": 37.3303463,
"longitude": -121.8890484,
"eta": 5
},
"destination": {
"latitude": 37.6213129,
"longitude": -122.3789554,
"eta": 19
},
"waypoints": [
{
"rider_id":null,
"latitude":37.77508531,
"type":"pickup",
"longitude":-122.3976683872
},
{
"rider_id":null,
"latitude":37.773133,
"type":"dropoff",
"longitude":-122.415069
},
{
"rider_id":"8KwsIO_YG6Y2jijSMf",
"latitude":37.7752423,
"type":"dropoff",
"longitude":-122.4175658
}
],
"riders": [
{
"rider_id":"8KwsIO_YG6Y2jijSMf",
"first_name":"Alec",
"me": true
},
{
"rider_id":null,
"first_name":"Kevin",
"me": false
}
]
}
The riders array, as specified in the GET /request/{request_id} reference page, is returned only for shared rides (uberPOOL rides). You will only be able to get a non-null rider_id if that rider account has already authenticated with your developer app.
This means that if any rider_id in the riders array is null, the rider account associated with that rider_id has not authenticated with your app.