How to get Video Thumbnails from api link? - flutter

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

Related

why can't I call my Model in My View page?

I'm trying to learn how to use APIs, but I've been struggling to get my code to work,
here is what I have so far ;
Provider :
class MovieProvider extends GetConnect {
#override
var queryParameters = {
'limit': '8',
'genres': 'comedia',
'sort': 'year',
'type': 'movies'
};
static const String _baseUrl = 'movies-app1.p.rapidapi.com';
void onInit() {
httpClient.baseUrl = _baseUrl;
}
static const Map<String, String> _headers = {
"x-rapidapi-key": "***************",
"x-rapidapi-host": "movies-app1.p.rapidapi.com",
};
// Base API request to get response
Future<dynamic> getStats() async {
Uri uri = Uri.https(_baseUrl, '/api/movies', queryParameters);
final response = await http.get(uri, headers: _headers);
print('provider IS WORKING');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
print("success");
print(response.body);
return json.decode(response.body);
} else {
print("not success");
// If that response was not OK, throw an error.
throw Exception('Failed to load json data');
}
}
}
Model :
import 'dart:convert';
Movies moviesFromJson(String str) => Movies.fromJson(json.decode(str));
String moviesToJson(Movies data) => json.encode(data.toJson());
class Movies {
Movies({
this.status,
this.success,
this.messageStatus,
this.results,
this.totalResults,
this.totalPages,
});
int? status;
bool? success;
String? messageStatus;
List<Result>? results;
int? totalResults;
int? totalPages;
factory Movies.fromJson(Map<String, dynamic> json) => Movies(
status: json["status"],
success: json["success"],
messageStatus: json["messageStatus"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
totalResults: json["total_results"],
totalPages: json["total_pages"],
);
Map<String, dynamic> toJson() => {
"status": status,
"success": success,
"messageStatus": messageStatus,
"results": List<dynamic>.from(results!.map((x) => x.toJson())),
"total_results": totalResults,
"total_pages": totalPages,
};
}
class Result {
Result({
this.actors,
this.directors,
this.escritors,
this.otherTitles,
this.id,
this.image,
this.title,
this.rating,
this.year,
this.titleOriginal,
this.uuid,
this.description,
this.genres,
this.countries,
this.release,
this.embedUrls,
this.index,
this.episodes,
this.createdAt,
this.updatedAt,
});
List<dynamic>? actors;
List<dynamic>? directors;
List<dynamic>? escritors;
List<dynamic>? otherTitles;
String? id;
String? image;
String? title;
String? rating;
String? year;
String? titleOriginal;
String? uuid;
String? description;
List<Country>? genres;
List<Country>? countries;
String? release;
List<EmbedUrl>? embedUrls;
int? index;
List<dynamic>? episodes;
DateTime? createdAt;
DateTime? updatedAt;
factory Result.fromJson(Map<String, dynamic> json) => Result(
actors: List<dynamic>.from(json["actors"].map((x) => x)),
directors: List<dynamic>.from(json["directors"].map((x) => x)),
escritors: List<dynamic>.from(json["escritors"].map((x) => x)),
otherTitles: List<dynamic>.from(json["otherTitles"].map((x) => x)),
id: json["_id"],
image: json["image"],
title: json["title"],
rating: json["rating"],
year: json["year"],
titleOriginal: json["titleOriginal"],
uuid: json["uuid"],
description: json["description"],
genres:
List<Country>.from(json["genres"].map((x) => Country.fromJson(x))),
countries: List<Country>.from(
json["countries"].map((x) => Country.fromJson(x))),
release: json["release"],
embedUrls: List<EmbedUrl>.from(
json["embedUrls"].map((x) => EmbedUrl.fromJson(x))),
index: json["index"],
episodes: List<dynamic>.from(json["episodes"].map((x) => x)),
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"actors": List<dynamic>.from(actors!.map((x) => x)),
"directors": List<dynamic>.from(directors!.map((x) => x)),
"escritors": List<dynamic>.from(escritors!.map((x) => x)),
"otherTitles": List<dynamic>.from(otherTitles!.map((x) => x)),
"_id": id,
"image": image,
"title": title,
"rating": rating,
"year": year,
"titleOriginal": titleOriginal,
"uuid": uuid,
"description": description,
"genres": List<dynamic>.from(genres!.map((x) => x.toJson())),
"countries": List<dynamic>.from(countries!.map((x) => x.toJson())),
"release": release,
"embedUrls": List<dynamic>.from(embedUrls!.map((x) => x.toJson())),
"index": index,
"episodes": List<dynamic>.from(episodes!.map((x) => x)),
"createdAt": createdAt?.toIso8601String(),
"updatedAt": updatedAt?.toIso8601String(),
};
}
class Country {
Country({
this.name,
this.uuid,
});
String? name;
String? uuid;
factory Country.fromJson(Map<String, dynamic> json) => Country(
name: json["name"],
uuid: json["uuid"],
);
Map<String, dynamic> toJson() => {
"name": name,
"uuid": uuid,
};
}
class EmbedUrl {
EmbedUrl({
this.server,
this.url,
this.priority,
});
String? server;
String? url;
int? priority;
factory EmbedUrl.fromJson(Map<String, dynamic> json) => EmbedUrl(
server: json["server"],
url: json["url"],
priority: json["priority"],
);
Map<String, dynamic> toJson() => {
"server": server,
"url": url,
"priority": priority,
};
}
Controller :
class HomeController extends GetxController {
var m = Movies();
var r = new Result();
final provider = Get.put(MovieProvider());
final count = 0.obs;
#override
void onInit() {
provider.getStats();
super.onInit();
}
#override
void onReady() {
super.onReady();
}
#override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
And as for my View I've been so far just testing to get the title of one of the movies as a Text, using :
Text(controller.r.titleOriginal[0])
But I get an error related to Null-safety,
I tried adding a '!' in !titleOriginal, but this is what I go :
Exception has occurred.
_CastError (Null check operator used on a null value)
adding '?' doesn't work either.
Here's also my View :
class DigiappstoreView extends GetView<DigiappstoreController> {
const DigiappstoreView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text(controller.r.titleOriginal![0])));
}
}
You are returning dynamic type from your provider. You should return a specific type. As per the code, it should return the type of Movie.
class MovieProvider extends GetConnect {
#override
var queryParameters = {
'limit': '8',
'genres': 'comedia',
'sort': 'year',
'type': 'movies'
};
static const String _baseUrl = 'movies-app1.p.rapidapi.com';
void onInit() {
httpClient.baseUrl = _baseUrl;
}
static const Map<String, String> _headers = {
"x-rapidapi-key": "***************",
"x-rapidapi-host": "movies-app1.p.rapidapi.com",
};
// Base API request to get response
Future<Movie> getStats() async {
Uri uri = Uri.https(_baseUrl, '/api/movies', queryParameters);
final response = await http.get(uri, headers: _headers);
print('provider IS WORKING');
if (response.statusCode == 200) {
return moviesFromJson(response.body);
} else {
throw Exception('Failed to load json data');
}
}
}
Also, in controller, you should assign the result to the variable like
class HomeController extends GetxController {
var m = Movies();
var r = Result();
final provider = Get.put(MovieProvider());
#override
void onInit() {
getStates();
super.onInit();
}
getStates() async {
movies = await provider.getStats();
r = movies.results;
update();
}
}
Now
in your view, wrap the child inside GetBuilder to update the UI once the data is updated.
class DigiappstoreView extends GetView<DigiappstoreController> {
const DigiappstoreView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(body: GetBuilder<DigiappstoreController>(
init: DigiappstoreController(),
builder: (controller) {
return Center(child: Text(controller.r == null ? '' : controller.r[0].titleOriginal!));
},
));
}
}
There may be some syntax error as i have not tried the code myself but these are the updates that you need to do.
I think you need to read the GetX Documentation in detail to know how it works

NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null

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

LateInitializationError: Field '___' has not been initialized

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

Cannot get data API Flutter

I want to get data of each element inside "invoices" to show but I don't know why it has a problem when I try to call "DataAllInvoice" class.
Please help me fix this problem.
Data API
{
"invoices": [
{
"id": 3,
"customer_id": 6,
"customer_name": "Nguyễn Công Phượng",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-16T10:05:43",
"total": 411107.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 4
},
{
"id": 2,
"customer_id": 3,
"customer_name": "Nguyễn Văn A",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-14T10:05:43",
"total": 411107.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 1
},
{
"id": 1,
"customer_id": 3,
"customer_name": "Nguyễn Văn A",
"creater_id": 2,
"creater_name": "Lê Minh Tuấn",
"create_time": "2021-05-14T09:28:43",
"total": 222220.0,
"description": "ABC",
"manager_confirm_id": 0,
"manager_confirm_name": null,
"manager_confirm_date": null,
"customer_confirm_date": null,
"status_id": 5
}
],
"total": 3
}
Class to call API
class GetInvoice{
static int statusInvoice;
createInvoice() async {
final response = await http.get(
Uri.parse("http://3.137.137.156:5000/api/rtm/v1/invoice/get-invoice?customer_id=0&pageNum=10&pageNo=1&from=%20&to=2021-05-14%2012%3A00%3A00"),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMTIzNDU2Nzg4IiwiaWF0IjoxNjIyNjI0MjAyLCJleHAiOjE2MjMyMjkwMDJ9.zkf23Da4-TR5sVZgtXjXvczERhaNT1teeX5k-mQaKK6lbE0l28j5TwY5ZqPL252AEAaT8W1jyEUijG-rQiSu5Q',
},
);
print("Status getApi Invoice:${response.statusCode}");
statusInvoice = response.statusCode;
if (response.statusCode == 200) {
Invoice invoice = Invoice.fromJson(jsonDecode(response.body));
List<DataAllInvoice> _invoice;
for(int i=0;i < invoice.invoices.length;i++){
if(invoice.invoices[i]!=null){
Map<String,dynamic> map=invoice.invoices[i];
_invoice.add(DataAllInvoice.fromJson(map)); ****Not working here****
}
}
return _invoice;
} else {
// throw an exception.
throw Exception('Failed to load data');
}
}
Class have a problem when I try to call - DataAllInvoice class
class DataAllInvoice {
final int id, customer_id, creater_id, total, manager_confirm_id, status_id;
final String customer_name, manager_confirm_name;
final String creater_name, description;
final DateTime create_time, manager_confirm_date, customer_confirm_date;
DataAllInvoice(
{this.id,
this.customer_id,
this.creater_id,
this.total,
this.manager_confirm_id,
this.status_id,
this.customer_name,
this.manager_confirm_name,
this.creater_name,
this.description,
this.create_time,
this.manager_confirm_date,
this.customer_confirm_date
});
factory DataAllInvoice.fromJson(Map<String, dynamic> json) {
return DataAllInvoice(
id: json[" id"],
customer_id: json[" customer_id"],
creater_id: json[" creater_id"],
total: json[" total"],
manager_confirm_id: json[" manager_confirm_id"],
status_id: json[" status_id"],
customer_name: json[" customer_name"],
manager_confirm_name: json[" manager_confirm_name"],
creater_name: json[" creater_name"],
description: json[" description"],
create_time: DateTime.parse(json[" create_time"]),
manager_confirm_date: DateTime.parse(json[" manager_confirm_date"]),
customer_confirm_date: DateTime.parse(json[" customer_confirm_date"]),
);
}
}
Invoice Class
class Invoice {
final List invoices;
final int total;
Invoice({this.invoices, this.total});
factory Invoice.fromJson(Map<String, dynamic> json) {
return Invoice(
invoices: json["invoices"],
total: json["total"],
);
}
}
Try That :
So here Fetch Api Class
Sometime you gotta need to use Uri.parse() to put the URL inside it.
and you have to check the statusCode is equal 200 Otherwise there is problem.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'DataCardFromApi.dart';
class FetchApi {
static Future<List<Articles>> fetchStory() async {
var url = Uri.parse("https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=c5609b49c9274e89bacde5dcab5c52a2");
http.Response response = await http.get(url);
if (response.statusCode == 200) {
Map<String, dynamic> resMap = jsonDecode(response.body);
List listNews = resMap['articles'];
return listNews.map((e) => Articles.fromJson(e)).toList();
}
return null;
}
}
So the second Step :
you have to copy All Code Of Json and convert to Dart Code via This Link
You will get a code like this :
class NewsModel {
String status;
int totalResults;
List<Articles> articles;
NewsModel({this.status, this.totalResults, this.articles});
NewsModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
totalResults = json['totalResults'];
if (json['articles'] != null) {
articles = new List<Articles>();
json['articles'].forEach((v) {
articles.add(new Articles.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['totalResults'] = this.totalResults;
if (this.articles != null) {
data['articles'] = this.articles.map((v) => v.toJson()).toList();
}
return data;
}
}
class Articles {
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
String publishedAt;
String content;
Articles(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
Articles.fromJson(Map<String, dynamic> json) {
source =
json['source'] != null ? new Source.fromJson(json['source']) : null;
author = json['author'];
title = json['title'];
description = json['description'];
url = json['url'];
urlToImage = json['urlToImage'];
publishedAt = json['publishedAt'];
content = json['content'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.source != null) {
data['source'] = this.source.toJson();
}
data['author'] = this.author;
data['title'] = this.title;
data['description'] = this.description;
data['url'] = this.url;
data['urlToImage'] = this.urlToImage;
data['publishedAt'] = this.publishedAt;
data['content'] = this.content;
return data;
}
}
class Source {
String id;
String name;
Source({this.id, this.name});
Source.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
The Third step :
you have to create a Function loadData like this and after that you will put it inside initState to get data
watch this code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/StoryModel.dart';
import 'Fetch_Api.dart';
import 'New_Page.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Articles> listModel;
#override
void initState() {
// TODO: implement initState
super.initState();
loadData() ;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(""),
actions: [
Padding(padding: EdgeInsets.only(right: 20.0),child: Icon(Icons.search_rounded))],
backgroundColor: Colors.indigo,
),
body: SafeArea(child: listModel != null ? ListView.builder(
shrinkWrap: true,
itemCount: listModel.length,
itemBuilder: (_ , index){
Articles model = listModel[index] ;
if(model.urlToImage != null)
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
InkWell(
onTap:()=> onPressCallback(model),
child: ClipRRect(
borderRadius: BorderRadius.circular(30.0),
child: Image.network(model.urlToImage,)),),
Text(model.title,style: TextStyle(fontSize: 27.0,fontWeight:FontWeight.bold),),
SizedBox(height: 20,),],
),
) ;
return SizedBox();
}) : Center(child: Text('Loading data ... ')),)
);
}
void loadData() async{
listModel = await FetchApi.fetchStory() ;
setState(() {});
}
void onPressCallback(Articles model) {
Navigator.push(context, MaterialPageRoute(builder: (_) => NewPage(model: model)));
}
}

How to fetch json data and separate it based on a Parameter?

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