Flutter: How to load JSON into a PageView - flutter

I'm hoping someone can tell me how to load JSON in to a PageView. Each page in the PageView will contain a ListView which will use Card widgets to display each Job from the JSON.
The JOB_DATE will dictate which page the job is displayed on. So in the JSON below, the first 3 items are on one date and the next 2 items are on the following date. So page 1 should display the first 3 items and page 2 should display items 4 & 5.
JSON :
{
"rows":[
{ "JOBID":23, "JOB_DATE":1588809600000, "START_TIME":"07:30", "JOB_NAME":"Cleaner" },
{ "JOBID":24, "JOB_DATE":1588809600000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":25, "JOB_DATE":1588809600000, "START_TIME":"12:30", "JOB_NAME":"Caretaker" }
{ "JOBID":26, "JOB_DATE":1588896000000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":27, "JOB_DATE":1588896000000, "START_TIME":"13:30", "JOB_NAME":"Caretaker" }
]
}
How would I code this to split the JSON up to the different pages?
Thanks heaps for any help.
Cheers,
Paul

You can you groupBy function from 'package:collection/collection.dart'
var json = {
"rows":[
{ "JOBID":23, "JOB_DATE":1588809600000, "START_TIME":"07:30", "JOB_NAME":"Cleaner" },
{ "JOBID":24, "JOB_DATE":1588809600000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":25, "JOB_DATE":1588809600000, "START_TIME":"12:30", "JOB_NAME":"Caretaker" }
{ "JOBID":26, "JOB_DATE":1588896000000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":27, "JOB_DATE":1588896000000, "START_TIME":"13:30", "JOB_NAME":"Caretaker" }
]
}
List<Map<String, dynamic> rows = json['rows']
Map<dynamic, List<Map<String, dynamic>> sortedRow = groupBy(rows, (row) => row['JOB_DATE']
And you will have a map where keys are (1588809600000, 1588896000000) and values are lists of your objects.
After that you can create PageView with a ListView of your objects

I would use something like this Json to dart class converter to quickly get a dart class for you JSON data structure. Then I would use the resulting dart class to parse your Json into a list of jobs in dart and then use that list on a specific page's ListView data source by only selecting the values with the specific sTARTTIME value you want to display on that page.
class Job {
List<Rows> rows;
Job({this.rows});
Job.fromJson(Map<String, dynamic> json) {
if (json['rows'] != null) {
rows = new List<Rows>();
json['rows'].forEach((v) {
rows.add(new Rows.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.rows != null) {
data['rows'] = this.rows.map((v) => v.toJson()).toList();
}
return data;
}
}
class Rows {
int jOBID;
int jOBDATE;
String sTARTTIME;
String jOBNAME;
Rows({this.jOBID, this.jOBDATE, this.sTARTTIME, this.jOBNAME});
Rows.fromJson(Map<String, dynamic> json) {
jOBID = json['JOBID'];
jOBDATE = json['JOB_DATE'];
sTARTTIME = json['START_TIME'];
jOBNAME = json['JOB_NAME'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['JOBID'] = this.jOBID;
data['JOB_DATE'] = this.jOBDATE;
data['START_TIME'] = this.sTARTTIME;
data['JOB_NAME'] = this.jOBNAME;
return data;
}
}
You can parse our JSON like this in your flutter app:
import 'dart:convert';
...
Job jobs = Job.fromJson(json.decode(jsonString));
...
final firstPageData = jobs.rows.where((row) => row.jOBDATE == 1588809600000).toList();
final secondPageData = jobs.rows.where((row) => row.jOBDATE == 1588896000000).toList();

Related

Flutter How to convert List into and from JSON

There are two Functions that I use to convert two String variables into JSON and from JSON.
String toJson() {
Map<String,dynamic> map = {'name': name,'count':checkListCount,'description':description,};
return jsonEncode(map)
}
fromJson(String context){
Map<String,dynamic> map = jsonDecode(contents)
name = map['name'];
description = map['description'];
return '0';
}
How i can use this to functions to covert List?
There is my list
List<CheckListPoint> checkListPoints = [];
CheckListPoint{
bool correctly = false;
bool passed = false;
String requirement = '';
}
variables that I have in CheckListPoint will change by the user later in the app.
i am not exactly getting which key will give you the list of data from your question,
but suppose you have a response in with "data" key is giving you list of items,
then you can add from JSON with ->
data : List<User>.from(json["data"].map((x) => User.fromJson(x))),
and to convert it to JSON you need
"data": List<dynamic>.from(data.map((x) => x.toJson())),
i hope this is what you are asking for
I did a very similiar thing when fetching messages from firebase. It's the same as parsing from JSON since both values are dynamic.
Here I convert a DataSnapshot to a List
Future<List<Message>> getMessages(DataSnapshot snapshot) async {
List<Message> msgs = List.empty(growable: true);
if(snapshot.value != null) {
Map<dynamic, dynamic> messages = snapshot.value;
messages.forEach((key, value) {
msgs.add(Message.fromFirebase(value));
});
}
return msgs;
}
And here is the Message class:
class Message {
String message;
String senderId;
int time;
Message.fromFirebase(Map<dynamic, dynamic> json) :
message = json["message"],
senderId = json["senderId"],
time = json["time"];
}

Adding firestore subcollection fields into List

i am trying to add the fields of a subcollection into reviewsList. May i know how should I do that in the //To add to List// part?
The 'Reviews' collection contains 2 subcollections namely '1' and '2'. Both '1' and '2' each contain a map of 4 fields.
Below are the codes and screenshot of firestore:
List<dynamic> reviewsList = [];
Future _getReviews() async{
firestore.collection('shops').doc(widget.shop.id).collection('reviews').get()
.then((reviews){
reviews.docs.forEach((result) {
firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id)
.get().then((reviewDocumentSnapshot) {
// To add to List //
});
});
});
}
the issue is related to misunderstanding of async. change your function as
Future _getReviews() async{
var reviews = await firestore.collection('shops').doc(widget.shop.id).collection('reviews').get();
reviews.docs.forEach((result) {
var reviewDocumentSnapshot= await firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id);
//add this snapshot to list.
reviewsList[your_object.fromJson(reviewDocumentSnapshot)];
});
}
and your model class will be
class your_model {
String name;
String review;
int star;
String uid;
your_model({this.name, this.review, this.star, this.uid});
your_model.fromJson(Map<String, dynamic> json) {
name = json['name'];
review = json['review'];
star = json['star'];
uid = json['uid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['review'] = this.review;
data['star'] = this.star;
data['uid'] = this.uid;
return data;
}
}

Unable to access list item inside a class

I've been wrapping my head around this issue for the past 2 hours (keep in mind that I'm new to Flutter). I'm trying to check if I've set up everything properly for getting a movie list from OMDB. Everything seems okay except the fact that I don't know how to access something inside a list ie. originalTitle.
This is the model:
class MovieItem {
int page;
int totalResults;
int totalPages;
List<Results> results;
MovieItem({this.page, this.totalResults, this.totalPages, this.results});
MovieItem.fromJson(Map<String, dynamic> json) {
page = json['page'];
totalResults = json['total_results'];
totalPages = json['total_pages'];
if (json['results'] != null) {
results = new List<Results>();
json['results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['page'] = this.page;
data['total_results'] = this.totalResults;
data['total_pages'] = this.totalPages;
if (this.results != null) {
data['results'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String posterPath;
int id;
String originalLanguage;
String originalTitle;
String title;
Results(
{this.posterPath,
this.id,
this.originalLanguage,
this.originalTitle,
this.title,});
Results.fromJson(Map<String, dynamic> json) {
posterPath = json['poster_path'];
id = json['id'];
originalLanguage = json['original_language'];
originalTitle = json['original_title'];
title = json['title'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['poster_path'] = this.posterPath;
data['id'] = this.id;
data['original_language'] = this.originalLanguage;
data['original_title'] = this.originalTitle;
data['title'] = this.title;
return data;
}
}
You are attempting to call a property on a List<Result> instead of Result. The property you are attempting to access exists on Result ... if there is a List of Result objects, what do you expect to return with movieItem.results.originalTitle? There could be any number of Result object with possibly different titles? If you just want to print them all out:
Future<MovieItem> movieItem() async {
var movieItem = await
client.movieItem();
movieItem.results.forEach((result) => print(result.originalTitle));
return movieItem;
}
The forEach will allow you to call the property and print it on every Result in the list
Your movieItem model class has list of result objects. So when you call the client.movieItem method the you get a MovieItem Object, and it you want to print the specific result item then just do this
print(movieItem.results[0].originalTitle)
and if you want to access all the objects from the result list then using for loop you can achieve it
for(int i=0;i<movieItem.results.length;i++)
{
print(movieItem.results[i].originalTitle);
}

List<Object> conversion from netcore server api in Flutter Dart

I am trying to convert a list of objects(List<Object> in Flutter) to a defined type(class) in a flutter project. I have tried examples on converting the list as shown in Serializing Your Object in Flutter . Every time I get Map<String, dynamic> is not a subtype of List<dynamic>. But tried something different, same error. Posted is the sample code for the latter not from Serializing Your Object in Flutter. Is there an alternative to achieving this? Really appreciate your responses. [Updated]
Custom Object
#JsonSerializable(explicitToJson: true)
class Activity{
String id;
String name;
double amount;
Activity({ this.amount, this.name , this.id});
Activity.fromJson(Map<String, dynamic> json){
id = json["id"];
name = json["name"];
amount = json["amount"];
}
Map<String, dynamic> toJson() => {
'id' : id,
'name' : name,
'amount' : amount,
};
}
Sample Flutter Screen
initiateConnection(){
var builder = HubConnectionBuilder();
this._hubConnection = builder.withUrl("##########################").build();
_hubConnection.onclose( (error) => print("Connection Closed"));
this._hubConnection.on("Activities", formActivityDashboard );
this._hubConnection.start().then((data) => print("Connected"));
}
formActivityDashboard(List<Object> data){
final items = (data).map((i) => new Activity.fromJson(i));
for (final item in items) {
print(item.id);
}
}
List<dynamic>ActivityList=json.decode(response.body);
List<Activity> myActivityList = new List();
for(int i=0;i<ActivityList.length;i++)
{
Map<String, dynamic>ActivityData = ActivityList.elementAt(i);
Activity act=new Activity();
act.id=ActivityData['id']
act.name=ActivityData['name']
act.amount=ActivityData['amount']
myActivityList.add(act);
}

How to convert an array to a dart object

I have the following structure that is returned from my API. How do I convert it to a dart object?
[
{
"stateName": "Alabama",
"stateAbbr": "AL"
},
{
"stateName": "Alaska",
"stateAbbr": "AK"
}
]
Basically, I want to display a flutter dropdown box with the stateName value..
It's a list of maps.
first make a State class:
class State{
final String stateName;
final String stateAbbr;
State({
this.stateName,
this.stateAbbr,
}) ;
factory State.fromJson(Map<String, dynamic> json){
return new State(
id: json['stateName'],
title: json['stateAbbr'],
);
}
}
then list of States:
class StatesList {
final List<State> States;
StatesList({
this.States,
});
factory StatesList.fromJson(List<dynamic> parsedJson) {
List<State> States = new List<State>();
States = parsedJson.map((i)=>State.fromJson(i)).toList();
return new StatesList(
States: States,
);
}
}
for more information read this article
class State {
String stateName;
String stateAbbr;
State({this.stateName, this.stateAbbr});
State.fromJson(Map<String, dynamic> json) {
stateName = json['stateName'];
stateAbbr = json['stateAbbr'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['stateName'] = this.stateName;
data['stateAbbr'] = this.stateAbbr;
return data;
}
}
use this website [https://javiercbk.github.io/json_to_dart/][1] it can help you to convert any object JSON to Dart class, and after that, you should use List Object of type State.