I wants to collect data of similar value in one variable in flutter to further use in drop down selection - flutter

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();

Related

Dart - Convert Map of objects fetched via HTTP REST-API

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
}

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 :)

How to pass a list of json to body of http Post request in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
submitQuestions() async {
var headers = {
'Content-Type': 'application/json',
'x-auth-token': '123edrfe33ewed'
};
var request = http.Request('POST', Uri.parse('url'));
request.body = json.encode({
"school_id": "123",
"teacher_id": "123",
"observer_id": "123",
"subject_id": "123",
"subject_name": "abc",
"class_id": "123",
"batch_id": "123",
"topic": "topic",
"academic_year": "2019-2020",
"remarks_data": [
{
"_id": "123",
"heading": "heading",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 4
},
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 1
}
]
},
{
"_id": "123",
"heading": "abc",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 3
}
]
}
]
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
}
This json will change dynamically when the number of questions increase. I cannot place this json file in the body like this. How to Do this one.
Wrap each list of json with jsonEncode
like:
"remarks_data": jsonEncode(..)
and do not forget to import.
import 'dart:convert';
The request body try to use Map data type. You can create a model class to deal with it.
Example
class School {
String school_id;
String teacher_id;
String observer_id;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['school_id'] = this.school_id;
data['teacher_id'] = this.teacher_id;
data['observer_id'] = this.observer_id;
...
return data;
}
}
/// Make sure your _school got data
School _school;
request.body = _school.toJson();

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;

Flutter return array from response from server

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)));