I got LateInitializationError: Field '_subjects#100178445' has not been initialized Error for Following Code.
Json Response as below.
{
"success": 1,
"subject": [
{
"subject_id": "5e32874c714fa",
"subject_name": "Account",
"image": "upload/subject/Account.png",
"active": "1",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344"
},
{
"subject_id": "5da9ff659fb7c",
"subject_name": "Biology",
"image": "upload/subject/03_logo-1164x484.png",
"active": "1",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344"
},
{
"subject_id": "5da9ff990b1c6",
"subject_name": "Chemisty",
"image": "upload/subject/02_logo-1168x490.png",
"active": "1",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344"
},
{
"subject_id": "5de76afbd064e",
"subject_name": "Computer",
"image": "upload/subject/07_logo-1169x486.png",
"active": "1",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344"
},
{
"subject_id": "5d788906c431b",
"subject_name": "Devsatya Paperset March 2020",
"image": "upload/subject/04_logo-1174x491.png",
"active": "1",
"standard_id": "5d1594e283e1a",
"medium_id": "5d15938aa1344"
}
]
}
Model class as bellow in subject_model.dart file.
// To parse this JSON data, do
//
// final subjectByUser = subjectByUserFromJson(jsonString);
import 'dart:convert';
SubjectByUser subjectByUserFromJson(String str) =>
SubjectByUser.fromJson(json.decode(str));
String subjectByUserToJson(SubjectByUser data) => json.encode(data.toJson());
class SubjectByUser {
SubjectByUser({
required this.success,
required this.subject,
});
int success;
List<Subject> subject;
factory SubjectByUser.fromJson(Map<String, dynamic> json) => SubjectByUser(
success: json["success"],
subject:
List<Subject>.from(json["subject"].map((x) => Subject.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"subject": List<dynamic>.from(subject.map((x) => x.toJson())),
};
}
class Subject {
Subject({
required this.subjectId,
required this.subjectName,
required this.image,
required this.active,
required this.standardId,
required this.mediumId,
});
String subjectId;
String subjectName;
String image;
String active;
String standardId;
String mediumId;
factory Subject.fromJson(Map<String, dynamic> json) => Subject(
subjectId: json["subject_id"],
subjectName: json["subject_name"],
image: json["image"],
active: json["active"],
standardId: json["standard_id"],
mediumId: json["medium_id"],
);
Map<String, dynamic> toJson() => {
"subject_id": subjectId,
"subject_name": subjectName,
"image": image,
"active": active,
"standard_id": standardId,
"medium_id": mediumId,
};
}
I created Function as below in apimanager.dart file
class ApiManager {
static const String subjectUrl =
"http://192.168.43.160/sahjanand/api/subject/get_by_user_plan?user_id=609cab2cd5b6c&order_id=1620889722609cd07a601af469889697609cab2cd5b6c&standard_id=5d1594e283e1a&medium_id=5d15938aa1344";
static Future<List<SubjectByUser>> getSubjectByUser() async {
try {
final response = await http.get(Uri.parse(subjectUrl));
if (response.statusCode == 200) {
final List<SubjectByUser> subjects =
subjectByUserFromJson(response.body) as List<SubjectByUser>;
print(subjects);
return subjects;
} else {
return <SubjectByUser>[];
}
} catch (e) {
// ignore: deprecated_member_use
return <SubjectByUser>[];
}
}
}
And view code in homepage.dart file as bellow.
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<SubjectByUser> _subjects;
late bool _loading;
#override
void initState() {
// TODO: implement initState
super.initState();
_loading = true;
ApiManager.getSubjectByUser().then((subjects) {
setState(() {
_subjects = subjects;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Subjects'),
),
body: Center(
child: ListView.builder(
itemCount: null == _subjects ? 0 : _subjects.length,
itemBuilder: (context, index) {
SubjectByUser subjectByUser = _subjects[index];
return ListTile(
title: Text(subjectByUser.success.toString()),
subtitle: Text(subjectByUser.subject.length.toString()),
);
}),
),
);
}
}
i got the LateInitializationError: Field '_subjects#100178445' has not been initialized Error.
So please help me how i solve this error.
You are calling _subjects in ListView.builder to compare, but by that time _subjects are not initalized, So it throws an error, You can initialise
_subjects as empty list
final _subjects = <SubjectByUser>[];
then once you got data, you can add all to it.
ApiManager.getSubjectByUser().then((subjects) {
setState(() {
_subject..clear()..addAll(subjects);
_loading = false;
});
});
and in itemCount, you can simply have
itemCount: _subjects.length,
Try something like:
child: _subjects != null && _subjects.length.length > 0 ? ListView.builder(...) : CircularProgressIndicator();
Related
I'm trying to make a simple ListView with GetX but it gives me this error when starting the app "Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.", I'm new to flutter and dart, that's why I'm starting with the "easiest" and for work reasons they ask me to add GetX
Home
class HomePage extends GetView<HomeController> {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
// final homeController = Get.put(HomeController());
var title = "HomePage";
return Scaffold(
body: Obx(() {
HomeController controller = Get.find<HomeController>();
return controller.regionList.isEmpty
? const Center(
child: Text('No hay regiones'),
)
: ListView.builder(
itemCount: controller.regionList.length,
itemBuilder: (context, index) => ListTile(
title: Text(
controller.regionList[index].name,
)));
}),
);
}
}
Controller
class HomeController extends GetxController {
//late Regiones model;
var regionList = <Regiones>[].obs;
Future<List<Regiones>> getRegiones() async {
var response = await rootBundle.loadString('assets/response.json');
var results = (jsonDecode(response)['regions'] ?? []) as List;
return results.map((x) => Regiones.fromJson(x)).toList();
//return Regiones.fromJson(jsonDecode(response));
}
//Json['regions'] == null ? Null :
#override
Future<void> onInit() async {
// TODO: implement onInit
super.onInit();
regionList.assignAll(await getRegiones());
}
}
Json
{
"name": "Chile",
"regions": [
{
"name": "Arica y Parinacota",
"romanNumber": "XV",
"number": "15",
"abbreviation": "AP",
"communes": [
{ "name": "Arica", "identifier": "XV-1" },
{ "name": "Camarones", "identifier": "XV-2" },
{ "name": "General Lagos", "identifier": "XV-3" },
{ "name": "Putre", "identifier": "XV-4" }
]
},
{
...
Model
Regiones regionesFromJson(String str) => Regiones.fromJson(json.decode(str));
String regionesToJson(Regiones data) => json.encode(data.toJson());
class Regiones {
Regiones({
required this.name,
required this.regions,
});
String name;
List<Region> regions;
factory Regiones.fromJson(Map<String, dynamic> json) => Regiones(
name: json["name"],
regions:
List<Region>.from(json["regions"].map((x) => Region.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"regions": List<dynamic>.from(regions.map((x) => x.toJson())),
};
}
class Region {
Region({
required this.name,
required this.romanNumber,
required this.number,
required this.abbreviation,
required this.communes,
});
String? name;
String? romanNumber;
String? number;
String? abbreviation;
List<Commune> communes;
factory Region.fromJson(Map<String, dynamic> json) => Region(
name: json["name"],
romanNumber: json["romanNumber"],
number: json["number"],
abbreviation: json["abbreviation"],
communes: List<Commune>.from(
json["communes"].map((x) => Commune.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"romanNumber": romanNumber,
"number": number,
"abbreviation": abbreviation,
"communes": List<dynamic>.from(communes.map((x) => x.toJson())),
};
}
class Commune {
Commune({
required this.name,
required this.identifier,
});
String name;
String identifier;
factory Commune.fromJson(Map<String, dynamic> json) => Commune(
name: json["name"],
identifier: json["identifier"] ?? '',
);
Map<String, dynamic> toJson() => {
"name": name,
"identifier": identifier,
};
}
You call ['regions'] in two place:
1:
var results = (jsonDecode(response)['regions'] ?? []) as List;
2: inside Regiones.fromJson
so in your HomeController instead of this:
return results.map((x) => Regiones.fromJson(x)).toList();
try this:
return results.map((x) => Region.fromJson(x)).toList();
and then make your getRegiones return Future<List> like this:
Future<List<Regione>> getRegiones() async {
...
}
Occurs exception when I get the chapter list.
So how can I solve this problem?
Please help.
Here is my API response.
{
"success": 1,
"chapter": [
{
"chapter_id": "609cb13f497e3",
"chapter_name": "test",
"subject_id": "5e32874c714fa",
"medium_id": "5d15938aa1344",
"standard_id": "5d1594e283e1a",
"material": null,
"textbook": null,
"test_paper": null,
"test_paper_solution": null,
"subject_memory_map": null,
"active": "1"
}
]
}
The model class which I created in chapter_model.dart file.
// To parse this JSON data, do
//
// final chapterBySubjectModel = chapterBySubjectModelFromJson(jsonString);
import 'dart:convert';
ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));
String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());
class ChapterBySubjectModel {
ChapterBySubjectModel({
required this.success,
required this.chapter,
});
int success;
List<Chapter> chapter;
factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
success: json["success"],
chapter: List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"chapter": List<dynamic>.from(chapter.map((x) => x.toJson())),
};
}
class Chapter {
Chapter({
required this.chapterId,
required this.chapterName,
required this.subjectId,
required this.mediumId,
required this.standardId,
this.material,
this.textbook,
this.testPaper,
this.testPaperSolution,
this.subjectMemoryMap,
required this.active,
});
String chapterId;
String chapterName;
String subjectId;
String mediumId;
String standardId;
dynamic material;
dynamic textbook;
dynamic testPaper;
dynamic testPaperSolution;
dynamic subjectMemoryMap;
String active;
factory Chapter.fromJson(Map<String, dynamic> json) => Chapter(
chapterId: json["chapter_id"],
chapterName: json["chapter_name"],
subjectId: json["subject_id"],
mediumId: json["medium_id"],
standardId: json["standard_id"],
material: json["material"],
textbook: json["textbook"],
testPaper: json["test_paper"],
testPaperSolution: json["test_paper_solution"],
subjectMemoryMap: json["subject_memory_map"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"chapter_id": chapterId,
"chapter_name": chapterName,
"subject_id": subjectId,
"medium_id": mediumId,
"standard_id": standardId,
"material": material,
"textbook": textbook,
"test_paper": testPaper,
"test_paper_solution": testPaperSolution,
"subject_memory_map": subjectMemoryMap,
"active": active,
};
}
Method which i Created in api_manager.dart file.
Future<List<Chapter>> getChapterBySubject() async {
final chapterUrl =
'$baseUrl/subject/get_by_user_plan?user_id=609cab2cd5b6c&order_id=1620889722609cd07a601af469889697609cab2cd5b6c&standard_id=5d1594e283e1a&medium_id=5d15938aa1344';
final response = await http.get(Uri.parse(chapterUrl));
if (response.statusCode == 200) {
final chapterData = chapterBySubjectModelFromJson(response.body);
final List<Chapter> chapters = chapterData.chapter;
print(chapters);
return chapters;
} else {
return <Chapter>[];
}
}
And view as below in chapter_widget.dart file.
class _ChapterWidgetState extends State<ChapterWidget> {
late bool _loading;
var _chapters = <Chapter>[];
#override
void initState() {
super.initState();
_loading = true;
ApiManager().getChapterBySubject().then((chapters) {
setState(() {
_chapters = chapters;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: null == _chapters ? 0 : _chapters.length,
//itemCount: _chapters.length,
itemBuilder: (context, index) {
Chapter chapter = _chapters[index];
return Container(
padding: EdgeInsets.all(8),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: InkWell(
//child: Image.asset("assets/logos/listbackground.png"),
child: Text(chapter.chapterName),
),
),
),
);
});
}
}
It throws an Exception in Model Class in below line.
List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
You set chapter as required but it seems API says it can be null. So, you should convert your parameters from required to nullable like this:
import 'dart:convert';
ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));
String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());
class ChapterBySubjectModel {
ChapterBySubjectModel({
this.success,
this.chapter,
});
int success;
List<Chapter> chapter;
factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
success: json["success"] == null ? null : json["success"],
chapter: json["chapter"] == null ? null : List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success == null ? null : success,
"chapter": chapter == null ? null : List<Chapter>.from(chapter.map((x) => x)),
};
}
I want to display list of videos with thumbnails from api.
Here is the api response as below.
{
"success": 1,
"video": [
{
"video_id": "609cb28a0760c",
"url": "https://www.youtube.com/watch?v=EvvHNtlz20Q&list=RDEvvHNtlz20Q&start_radio=1",
"search_by": "",
"topic_id": "609cb1dce30aa",
"chapter_id": "609cb13f497e3",
"subject_id": "5e32874c714fa",
"medium_id": "5d15938aa1344",
"standard_id": "5d1594e283e1a",
"topic_name": "test topic",
"active": "1"
}
]
}
From above response i created Model Class as below in videomodel.dart file.
// To parse this JSON data, do
//
// final videoModel = videoModelFromJson(jsonString);
import 'dart:convert';
VideoModel videoModelFromJson(String str) =>
VideoModel.fromJson(json.decode(str));
String videoModelToJson(VideoModel data) => json.encode(data.toJson());
class VideoModel {
VideoModel({
required this.success,
required this.video,
});
int success;
List<Video> video;
factory VideoModel.fromJson(Map<String, dynamic> json) => VideoModel(
success: json["success"],
video: List<Video>.from(json["video"].map((x) => Video.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"video": List<dynamic>.from(video.map((x) => x.toJson())),
};
}
class Video {
Video({
required this.videoId,
required this.url,
required this.searchBy,
required this.topicId,
required this.chapterId,
required this.subjectId,
required this.mediumId,
required this.standardId,
required this.topicName,
required this.active,
});
String videoId;
String url;
String searchBy;
String topicId;
String chapterId;
String subjectId;
String mediumId;
String standardId;
String topicName;
String active;
factory Video.fromJson(Map<String, dynamic> json) => Video(
videoId: json["video_id"],
url: json["url"],
searchBy: json["search_by"],
topicId: json["topic_id"],
chapterId: json["chapter_id"],
subjectId: json["subject_id"],
mediumId: json["medium_id"],
standardId: json["standard_id"],
topicName: json["topic_name"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"video_id": videoId,
"url": url,
"search_by": searchBy,
"topic_id": topicId,
"chapter_id": chapterId,
"subject_id": subjectId,
"medium_id": mediumId,
"standard_id": standardId,
"topic_name": topicName,
"active": active,
};
}
Here is the Function i created in apimanager.dart file.
Future<List<Video>> getVideo() async {
final videoUrl =
"$baseUrl/videos/get_by_standard_medium_subject_chapter_id?subject_id=5e32874c714fa&medium_id=5d15938aa1344&standard_id=5d1594e283e1a&chapter_id=609cb13f497e3";
final response = await http.get(Uri.parse(videoUrl));
if (response.statusCode == 200) {
final videoData = videoModelFromJson(response.body);
final List<Video> videos = videoData.video;
return videos;
} else {
return <Video>[];
}
}
And last is view code as below in video_widget.dart file.
class _VideoWidgetState extends State<VideoWidget> {
var _videos = <Video>[];
late bool _loading;
#override
void initState() {
super.initState();
_loading = true;
ApiManager().getVideo().then((videos) {
setState(() {
_videos = videos;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: null == _videos ? 0 : _videos.length,
//itemCount: _subjects.length,
itemBuilder: (context, index) {
Video video = _videos[index];
});
}
}
So how can i display the list of videos with the thumbnails?
Simply using YoutubeVideoController I solved the problem.
ListView.builder(
itemCount: null == _videos ? 0 : _videos.length,
itemBuilder: (context, index) {
Video video = _videos[index];
var url = video.url;
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: YoutubePlayer.getThumbnail(videoId: url),
flags: YoutubePlayerFlags(
autoPlay: false,
mute: false,
disableDragSeek: false,
loop: false,
isLive: false,
forceHD: false,
),
);
return YoutubePlayer(
controller: _controller,
);
},
),
{"response":{"status":true,"message":null,"data":{"upcoming_match":[{"is_lineup":0,"series_id":115991,"match_id":45643,"guru_url":"","series_name":"DD20","local_team_id":115885,"local_team_name":"WCC","local_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/wcc.png","visitor_team_id":115892,"visitor_team_name":"DDC","visitor_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/ddc.png","star_date":"2020-09-12T00:00:00","star_time":"07:00","total_contest":0,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":115991,"match_id":45644,"guru_url":"","series_name":"DD20","local_team_id":115889,"local_team_name":"SD","local_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/sd.png","visitor_team_id":115890,"visitor_team_name":"PCC","visitor_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/pcc.png","star_date":"2020-09-12T00:00:00","star_time":"07:00","total_contest":7,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":116363,"match_id":45579,"guru_url":"","series_name":"IWS50","local_team_id":116365,"local_team_name":"SW","local_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/sw.png","visitor_team_id":116366,"visitor_team_name":"TW","visitor_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/tw.png","star_date":"2020-09-13T00:00:00","star_time":"15:00","total_contest":0,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":116531,"match_id":45501,"guru_url":"","series_name":"RHFT-2020","local_team_id":104877,"local_team_name":"VP","local_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/vp.png","visitor_team_id":104878,"visitor_team_name":"WS","visitor_team_flag":"http:\/\/sportsindia11.com\/\/uploads\/team_flag\/ws.png","star_date":"2020-09-13T00:00:00","star_time":"15:00","total_contest":0,"server_time":"2020-09-11 22:52:32"}],"live_match":[],"completed_match":[],"version_code":1,"apk_url":"http:\/\/sportsindia11.com\/\/sportsindia1101.apk"}}}
Check out this example that I have created:
This is the json that you provided:
{
"response": {
"status": true,
"message": null,
"data": {
"upcoming_match": [{
"is_lineup": 0,
"series_id": 115991,
"match_id": 45643,
"guru_url": "",
"series_name": "DD20",
"local_team_id": 115885,
"local_team_name": "WCC",
"local_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/wcc.png",
"visitor_team_id": 115892,
"visitor_team_name": "DDC",
"visitor_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/ddc.png",
"star_date": "2020-09-12T00:00:00",
"star_time": "07:00",
"total_contest": 0,
"server_time": "2020-09-11 22:52:32"
}, {
"is_lineup": 0,
"series_id": 115991,
"match_id": 45644,
"guru_url": "",
"series_name": "DD20",
"local_team_id": 115889,
"local_team_name": "SD",
"local_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/sd.png",
"visitor_team_id": 115890,
"visitor_team_name": "PCC",
"visitor_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/pcc.png",
"star_date": "2020-09-12T00:00:00",
"star_time": "07:00",
"total_contest": 7,
"server_time": "2020-09-11 22:52:32"
}, {
"is_lineup": 0,
"series_id": 116363,
"match_id": 45579,
"guru_url": "",
"series_name": "IWS50",
"local_team_id": 116365,
"local_team_name": "SW",
"local_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/sw.png",
"visitor_team_id": 116366,
"visitor_team_name": "TW",
"visitor_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/tw.png",
"star_date": "2020-09-13T00:00:00",
"star_time": "15:00",
"total_contest": 0,
"server_time": "2020-09-11 22:52:32"
}, {
"is_lineup": 0,
"series_id": 116531,
"match_id": 45501,
"guru_url": "",
"series_name": "RHFT-2020",
"local_team_id": 104877,
"local_team_name": "VP",
"local_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/vp.png",
"visitor_team_id": 104878,
"visitor_team_name": "WS",
"visitor_team_flag": "http:\/\/sportsindia11.com\/\/uploads\/team_flag\/ws.png",
"star_date": "2020-09-13T00:00:00",
"star_time": "15:00",
"total_contest": 0,
"server_time": "2020-09-11 22:52:32"
}],
"live_match": [],
"completed_match": [],
"version_code": 1,
"apk_url": "http:\/\/sportsindia11.com\/\/sportsindia1101.apk"
}
}
}
This is the model class for it:
// To parse this JSON data, do
//
// final events = eventsFromJson(jsonString);
import 'dart:convert';
Events eventsFromJson(String str) => Events.fromJson(json.decode(str));
String eventsToJson(Events data) => json.encode(data.toJson());
class Events {
Events({
this.response,
});
Response response;
factory Events.fromJson(Map<String, dynamic> json) => Events(
response: Response.fromJson(json["response"]),
);
Map<String, dynamic> toJson() => {
"response": response.toJson(),
};
}
class Response {
Response({
this.status,
this.message,
this.data,
});
bool status;
dynamic message;
Data data;
factory Response.fromJson(Map<String, dynamic> json) => Response(
status: json["status"],
message: json["message"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": data.toJson(),
};
}
class Data {
Data({
this.upcomingMatch,
this.liveMatch,
this.completedMatch,
this.versionCode,
this.apkUrl,
});
List<UpcomingMatch> upcomingMatch;
List<dynamic> liveMatch;
List<dynamic> completedMatch;
int versionCode;
String apkUrl;
factory Data.fromJson(Map<String, dynamic> json) => Data(
upcomingMatch: List<UpcomingMatch>.from(json["upcoming_match"].map((x) => UpcomingMatch.fromJson(x))),
liveMatch: List<dynamic>.from(json["live_match"].map((x) => x)),
completedMatch: List<dynamic>.from(json["completed_match"].map((x) => x)),
versionCode: json["version_code"],
apkUrl: json["apk_url"],
);
Map<String, dynamic> toJson() => {
"upcoming_match": List<dynamic>.from(upcomingMatch.map((x) => x.toJson())),
"live_match": List<dynamic>.from(liveMatch.map((x) => x)),
"completed_match": List<dynamic>.from(completedMatch.map((x) => x)),
"version_code": versionCode,
"apk_url": apkUrl,
};
}
class UpcomingMatch {
UpcomingMatch({
this.isLineup,
this.seriesId,
this.matchId,
this.guruUrl,
this.seriesName,
this.localTeamId,
this.localTeamName,
this.localTeamFlag,
this.visitorTeamId,
this.visitorTeamName,
this.visitorTeamFlag,
this.starDate,
this.starTime,
this.totalContest,
this.serverTime,
});
int isLineup;
int seriesId;
int matchId;
String guruUrl;
String seriesName;
int localTeamId;
String localTeamName;
String localTeamFlag;
int visitorTeamId;
String visitorTeamName;
String visitorTeamFlag;
DateTime starDate;
String starTime;
int totalContest;
DateTime serverTime;
factory UpcomingMatch.fromJson(Map<String, dynamic> json) => UpcomingMatch(
isLineup: json["is_lineup"],
seriesId: json["series_id"],
matchId: json["match_id"],
guruUrl: json["guru_url"],
seriesName: json["series_name"],
localTeamId: json["local_team_id"],
localTeamName: json["local_team_name"],
localTeamFlag: json["local_team_flag"],
visitorTeamId: json["visitor_team_id"],
visitorTeamName: json["visitor_team_name"],
visitorTeamFlag: json["visitor_team_flag"],
starDate: DateTime.parse(json["star_date"]),
starTime: json["star_time"],
totalContest: json["total_contest"],
serverTime: DateTime.parse(json["server_time"]),
);
Map<String, dynamic> toJson() => {
"is_lineup": isLineup,
"series_id": seriesId,
"match_id": matchId,
"guru_url": guruUrl,
"series_name": seriesName,
"local_team_id": localTeamId,
"local_team_name": localTeamName,
"local_team_flag": localTeamFlag,
"visitor_team_id": visitorTeamId,
"visitor_team_name": visitorTeamName,
"visitor_team_flag": visitorTeamFlag,
"star_date": starDate.toIso8601String(),
"star_time": starTime,
"total_contest": totalContest,
"server_time": serverTime.toIso8601String(),
};
}
This is the main ui with the sliverList:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: Login());
}
}
class Login extends StatefulWidget {
#override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
List<UpcomingMatch> upcomingMatches = List();
bool _isLoading = false;
#override
void initState() {
super.initState();
getData();
}
getData() async {
setState(() {
_isLoading = true;
});
String data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
print('This is the sttring : $data');
// I have taken the local String you just have to call you http request above.
// var response = await http.get('your url ') or same for http.post()
//when you get the response the and the pass to the below model.
// see the following example .
// final res = eventsFromJson(response.body);
// Comment this below when making the http call.
final res = eventsFromJson(data);
print('This is the data: ${json.encode(res)}');
upcomingMatches = res.response.data.upcomingMatch;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: _isLoading
? CircularProgressIndicator()
: CustomScrollView(slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Container(
child: Card(
child: Column(
children: <Widget>[
Text('This is seriesname: ${upcomingMatches[index].seriesName}'),
Text('This is series id :${upcomingMatches[index].seriesId}'),
],
),
),
);
},
childCount: upcomingMatches.length,
),
),
]),
));
}
}
Check out and let me know if it works.
I have a json object here -
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "cciigcigc",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
I want to fetch it based on the ["data"]["status"] parameter; if the status is false, return a seperate list and if the status is true, return another list. I have tried to modify my current fetch method this way -
Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false
List<Post> statusComplete;
List<Post> statusInComplete;
String link = baseURL + fetchTodoByDate;
// print("printing from get task = $setter");
Stopwatch stopwatchbefore = new Stopwatch()..start();
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});
print('fetch executed in ${stopwatchbefore.elapsed}');
if (res.statusCode == 200) {
Stopwatch stopwatchafter = new Stopwatch()
..start();
var data = json.decode(res.body);
var rest = data["data"] as List;
if(identifier == true){
statusComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusComplete;
}else if(identifier == false){
statusInComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusInComplete;
}
print('statuscode executed in ${stopwatchafter.elapsed}');
Future.delayed(Duration(seconds: 5));
}
// print("List Size: ${list.length}");
}
This is the first time I am trying to fetch and separate the data this way. I have tried to look at some tutorials but none seemed to be satisfying my case.
Could i get some suggestion on how to fetch the data and then separate it based on a parameter?
check out the example below which will give the basic idea how the flow works.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final yourData = dataFromJson(jsonString);
dataList = yourData.data;
var statusComplete = dataList.where((i) => i.status == true).toList();
for (int i = 0; i < statusComplete.length; i++) {
print('This is the list for true status :${statusComplete[i].title}');
}
var statusInComplete = dataList.where((i) => i.status == false).toList();
print(statusInComplete[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(dataList[index].status.toString());
}),
)),
);
}
}
below is the model class
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
String error;
String message;
List<Datum> data;
Data({
this.error,
this.message,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
and this is the json that you specified
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "first",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "second",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "third",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
Try this model class
import 'dart:convert';
Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
class Jsonmodel {
String error;
String message;
List<Datum> data;
Jsonmodel({
this.error,
this.message,
this.data,
});
factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
use like this
var res = await http.post(Uri.encodeFull(link), headers: {"Accept":
"application/json", }, body: {"date" : setter.toString()});
Jsonmodel modeldata = jsonmodelFromJson(res);
// do your stuff
modeldata.data.foreach((data){
if(data.status){
//do your stuff
}else{
//do your stuff
}
});