flutter building listview with response from restapi - flutter

typical json response:
{"data":[{"id":1,"partnerTypeId":1,"active":true,"name":"Covin - AINO UG","shortname":"Covin","firstname":null,"lastname":null,"addressId":1,"phoneId":null,"countryId":"in","email":"support#covin.in","web":"www.covin.in","infos":{},"note":null,"createdAt":"2021-03-06 23:30:30","updatedAt":"2021-03-06 23:30:30","updatedBy":null},{"id":41,"partnerTypeId":100,"active":true,"name":"Tester IND","shortname":"T.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"email#tester","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:02","updatedAt":"2021-03-07 01:25:06","updatedBy":null},{"id":42,"partnerTypeId":100,"active":true,"name":"MIT Charl","shortname":"KITA Ch.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"kisa1#kol","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:42","updatedAt":"2021-03-07 01:25:08","updatedBy":null}]}
Generated podo class:
filename- partnerList.dart
// To parse this JSON data, do
//
// final partnerList = partnerListFromMap(jsonString);
import 'dart:convert';
PartnerList partnerListFromMap(String str) => PartnerList.fromMap(json.decode(str));
String partnerListToMap(PartnerList data) => json.encode(data.toMap());
class PartnerList {
PartnerList({
this.data,
});
List<Datum> data;
factory PartnerList.fromMap(Map<String, dynamic> json) => PartnerList(
data: List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"data": List<dynamic>.from(data.map((x) => x.toMap())),
};
}
class Datum {
Datum({
this.id,
this.partnerTypeId,
this.active,
this.name,
this.shortname,
this.firstname,
this.lastname,
this.addressId,
this.phoneId,
this.countryId,
this.email,
this.web,
this.infos,
this.note,
this.createdAt,
this.updatedAt,
this.updatedBy,
});
int id;
int partnerTypeId;
bool active;
String name;
String shortname;
dynamic firstname;
dynamic lastname;
int addressId;
dynamic phoneId;
String countryId;
String email;
String web;
Infos infos;
dynamic note;
DateTime createdAt;
DateTime updatedAt;
dynamic updatedBy;
factory Datum.fromMap(Map<String, dynamic> json) => Datum(
id: json["id"],
partnerTypeId: json["partnerTypeId"],
active: json["active"],
name: json["name"],
shortname: json["shortname"],
firstname: json["firstname"],
lastname: json["lastname"],
addressId: json["addressId"] == null ? null : json["addressId"],
phoneId: json["phoneId"],
countryId: json["countryId"],
email: json["email"],
web: json["web"] == null ? null : json["web"],
infos: Infos.fromMap(json["infos"]),
note: json["note"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
updatedBy: json["updatedBy"],
);
Map<String, dynamic> toMap() => {
"id": id,
"partnerTypeId": partnerTypeId,
"active": active,
"name": name,
"shortname": shortname,
"firstname": firstname,
"lastname": lastname,
"addressId": addressId == null ? null : addressId,
"phoneId": phoneId,
"countryId": countryId,
"email": email,
"web": web == null ? null : web,
"infos": infos.toMap(),
"note": note,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"updatedBy": updatedBy,
};
}
class Infos {
Infos();
factory Infos.fromMap(Map<String, dynamic> json) => Infos(
);
Map<String, dynamic> toMap() => {
};
}
related fetch class: file name - partner.api.dart
import 'partnerList.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
Future<List<PartnerList>> fetchPartner() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final userid = prefs.getString('user_id');
final token = prefs.getString('token');
Map<String, String> requestHeaders = {
'Accept': 'application/json',
// "Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $token',
};
final response = await http.get("https://api.covin.in/partners/",
headers: requestHeaders);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response.body);
return partnerListFromMap(response.body);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load PartnerList');
}
}
Now the first error I am getting:
A value of type 'PartnerList' can't be returned from the function 'fetchPartner' because it has a return type of 'Future<List<PartnerList>>'.dartreturn_of_invalid_type
how I can fix this?
update: I have modified the function partnerListfromMap like below:
List<PartnerList> partnerListFromMap(String str) => List<PartnerList>.from(json.decode(str));
String partnerListToMap(PartnerList data) => json.encode(data.toMap());
but I am getting another error now:
Exception has occurred. _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>')

You can copy paste run full code below
Your json string is PartnerList not List<PartnerList>
You can use Future<PartnerList> and use return Future.value
code snippet
Future<PartnerList> fetchPartner() async {
...
return Future.value(partnerListFromMap(response.body));
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
PartnerList partnerListFromMap(String str) =>
PartnerList.fromMap(json.decode(str));
String partnerListToMap(PartnerList data) => json.encode(data.toMap());
class PartnerList {
PartnerList({
this.data,
});
List<Datum> data;
factory PartnerList.fromMap(Map<String, dynamic> json) => PartnerList(
data: List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"data": List<dynamic>.from(data.map((x) => x.toMap())),
};
}
class Datum {
Datum({
this.id,
this.partnerTypeId,
this.active,
this.name,
this.shortname,
this.firstname,
this.lastname,
this.addressId,
this.phoneId,
this.countryId,
this.email,
this.web,
this.infos,
this.note,
this.createdAt,
this.updatedAt,
this.updatedBy,
});
int id;
int partnerTypeId;
bool active;
String name;
String shortname;
dynamic firstname;
dynamic lastname;
int addressId;
dynamic phoneId;
String countryId;
String email;
String web;
Infos infos;
dynamic note;
DateTime createdAt;
DateTime updatedAt;
dynamic updatedBy;
factory Datum.fromMap(Map<String, dynamic> json) => Datum(
id: json["id"],
partnerTypeId: json["partnerTypeId"],
active: json["active"],
name: json["name"],
shortname: json["shortname"],
firstname: json["firstname"],
lastname: json["lastname"],
addressId: json["addressId"] == null ? null : json["addressId"],
phoneId: json["phoneId"],
countryId: json["countryId"],
email: json["email"],
web: json["web"] == null ? null : json["web"],
infos: Infos.fromMap(json["infos"]),
note: json["note"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
updatedBy: json["updatedBy"],
);
Map<String, dynamic> toMap() => {
"id": id,
"partnerTypeId": partnerTypeId,
"active": active,
"name": name,
"shortname": shortname,
"firstname": firstname,
"lastname": lastname,
"addressId": addressId == null ? null : addressId,
"phoneId": phoneId,
"countryId": countryId,
"email": email,
"web": web == null ? null : web,
"infos": infos.toMap(),
"note": note,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"updatedBy": updatedBy,
};
}
class Infos {
Infos();
factory Infos.fromMap(Map<String, dynamic> json) => Infos();
Map<String, dynamic> toMap() => {};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<PartnerList> _future;
Future<PartnerList> fetchPartner() async {
String jsonString = '''
{"data":[{"id":1,"partnerTypeId":1,"active":true,"name":"Covin - AINO UG","shortname":"Covin","firstname":null,"lastname":null,"addressId":1,"phoneId":null,"countryId":"in","email":"support#covin.in","web":"www.covin.in","infos":{},"note":null,"createdAt":"2021-03-06 23:30:30","updatedAt":"2021-03-06 23:30:30","updatedBy":null},{"id":41,"partnerTypeId":100,"active":true,"name":"Tester IND","shortname":"T.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"email#tester","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:02","updatedAt":"2021-03-07 01:25:06","updatedBy":null},{"id":42,"partnerTypeId":100,"active":true,"name":"MIT Charl","shortname":"KITA Ch.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"kisa1#kol","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:42","updatedAt":"2021-03-07 01:25:08","updatedBy":null}]}
''';
final response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response.body);
return Future.value(partnerListFromMap(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load PartnerList');
}
}
#override
void initState() {
_future = fetchPartner();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<PartnerList> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data.data[index].id
.toString()),
Spacer(),
Text(
snapshot.data.data[index].name,
),
],
),
));
});
}
}
}));
}
}

Try this:
// this is correct. I think you generated this using app.quicktype.io ? Then it's correct.
PartnerList partnerListFromMap(String str) => PartnerList.fromMap(json.decode(str));
// you want the list of Datum.
Future<List<Datum>> fetchPartner() async {
// other codes here ...
return partnerListFromMap(response.body).data;
// other codes here ...
}

Related

How to get data from api in flutter where response is inside of list?

The below given code in my response which I need to display in Listview builder, now I need the data of name which in inside result, how do i fetch it and display it in text?
{
"message": "sucess",
"error": false,
"code": 200,
"result": [
{
"id": 1,
"name": "Lab Report"
},
{
"id": 2,
"name": "News"
},
{
"id": 3,
"name": "X-ray"
},
{
"id": 8,
"name": "Blood Test"
}
],
"status": 200
}
And below is my model class of the response now I want the data which is inside of result and need to display in Listview builder
import 'dart:convert';
PostFromJson postFromJsonFromJson(String str) => PostFromJson.fromJson(json.decode(str));
String postFromJsonToJson(PostFromJson data) => json.encode(data.toJson());
class PostFromJson {
PostFromJson({
this.message,
this.error,
this.code,
required this.result,
this.status,
});
String? message;
bool? error;
int? code;
List<Result> result;
int? status;
factory PostFromJson.fromJson(Map<String, dynamic> json) => PostFromJson(
message: json["message"],
error: json["error"],
code: json["code"],
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
status: json["status"],
);
Map<String, dynamic> toJson() => {
"message": message,
"error": error,
"code": code,
"result": List<dynamic>.from(result.map((x) => x.toJson())),
"status": status,
};
}
class Result {
Result({
this.id,
this.name,
});
int? id;
String? name;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
Use this model
class Response{
final String message;
final bool error;
final int code;
final List<Result> result;
final int status;
const Response({required this.message,required this.error, required this.code,required this.result,required this.status});
factory Response.fromJson(Map<String, dynamic> json) {
List<Result> data = [];
data = json["result"]
.map<Result>((json) => Result.fromJson(json))
.toList();
return Response(
message:json['message'],
error: json['error'],
code: json['code'],
result: data,
status: json['status']
);
}
}
class Result{
final int id;
final String name;
const Result({ required this.id,required this.name});
factory Result.fromJson(Map<String, dynamic> json) {
return Result(
id: json['code'],
name:json['name'],
);
}
}
and declare a variable
Response? responseData;
set the api response in the responseData as Response
responseData = Response.fromJson(jsonDecode(response.body));
You can access the name inside the result like this,
responseData.result[index].name
Listview builder will be
return Container(
child: Column(
children: [
ListView.builder(
shrinkWrap: true,
itemCount: responseData?.result.length,
itemBuilder: (context,index) =>options(context,index)
)
],
),
);
Widget options(BuildContext context, int index){
return Text(responseData.result[index].name);
}
final name = data['result'][0].name;
final id = data['result'][0].id;
There are a lot of resources available online on how to fetching data, parsing, modeling, and showing in the UI (from API).
Here's one official doc from Flutter: https://docs.flutter.dev/cookbook/networking/fetch-data
EDIT (after adding the model):
final response = await http.get("url");
final post = postFromJsonFromJson(response);
//Use list with ListView.builder(...)
final results = post.result; //List<Result>
You must be getting the data from model you created, you can use your model like this
class MyWidget extends StatelessWidget {
PostFromJson data;
MyWidget(this.data);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: data.result.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: const Icon(Icons.list),
title: Text(data.result[index].id.toString()));
});
}
}

I cannot display my response in text widgets in flutter

I have used post method for user login which is successfully done and it returns responses in list which I need to display in text widget in some other class, but when I try to display it in text widget using Future builder it throws exception in my emulator but nothing shows in my console.
This is my APIService class, it works fine when I post details but when i try to display the response in text widget, it shows exception from this class, at the bottom of this code there is " throw Exception('Failed');" it shows this exception only when I try to display the response in text widgets.
class APIService {
Future<DoctorResponseLoginModels> register(
DoctorRequestLoginModels doctorLoginRequestModels) async {
String url = "http://202.51.75.142:9028/api/PatientMaster/PostPatientLogin";
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var globalToken = sharedPreferences.getString("token");
print("$globalToken");
http.Response response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
'Authorization': 'Bearer $globalToken',
},
body: jsonEncode(doctorLoginRequestModels));
var responseJson = json.decode(response.body.toString());
DoctorResponseLoginModels responseModel =
DoctorResponseLoginModels.fromJson(responseJson);
print("This is ${response.body}");
if (response.statusCode == 200) {
sharedPreferences.setInt('code', response.statusCode);
var StatusCode = sharedPreferences.getInt('code');
print("This contains : $StatusCode");
return DoctorResponseLoginModels.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed');
}
}
}
This is My DoctorRequestLoginModels class which I send to server.
DoctorRequestLoginModels doctorRequestLoginModelsFromJson(String str) =>
DoctorRequestLoginModels.fromJson(json.decode(str));
String doctorRequestLoginModelsToJson(DoctorRequestLoginModels data) =>
json.encode(data.toJson());
class DoctorRequestLoginModels {
DoctorRequestLoginModels({
required this.code,
required this.username,
required this.password,
});
String code;
String username;
String password;
factory DoctorRequestLoginModels.fromJson(Map<String, dynamic> json) =>
DoctorRequestLoginModels(
code: json["code"],
username: json["username"],
password: json["password"],
);
Map<String, dynamic> toJson() => {
"code": code,
"username": username,
"password": password,
};
}
This is my DoctorRespinseModels class which I need to display in text widgets.
DoctorResponseLoginModels doctorResponseLoginModelsFromJson(String str) =>
DoctorResponseLoginModels.fromJson(json.decode(str));
String doctorResponseLoginModelsToJson(DoctorResponseLoginModels data) =>
json.encode(data.toJson());
class DoctorResponseLoginModels {
DoctorResponseLoginModels({
this.doctorId,
this.nmCno,
this.doctorName,
this.contactNo,
this.username,
this.emailId,
this.strEmail,
this.id,
this.intMobile,
this.gender,
this.currentAddress,
this.depId,
this.entryDate,
this.password,
this.code,
this.isActive,
this.hospitalName,
this.department,
this.deviceId,
this.profile,
this.token,
this.role,
});
int? doctorId;
String? nmCno;
String? doctorName;
String? contactNo;
dynamic? username;
String? emailId;
String? strEmail;
int? id;
String? intMobile;
dynamic? gender;
String? currentAddress;
int? depId;
String? entryDate;
dynamic? password;
dynamic? code;
bool? isActive;
dynamic? hospitalName;
dynamic? department;
dynamic? deviceId;
String? profile;
String? token;
String? role;
factory DoctorResponseLoginModels.fromJson(Map<String, dynamic> json) =>
DoctorResponseLoginModels(
doctorId: json["doctorID"],
nmCno: json["nmCno"],
doctorName: json["doctorName"],
contactNo: json["contactNo"],
username: json["username"],
emailId: json["emailID"],
strEmail: json["strEmail"],
id: json["id"],
intMobile: json["intMobile"],
gender: json["gender"],
currentAddress: json["currentAddress"],
depId: json["depId"],
entryDate: json["entryDate"],
password: json["password"],
code: json["code"],
isActive: json["isActive"],
hospitalName: json["hospitalName"],
department: json["department"],
deviceId: json["deviceId"],
profile: json["profile"],
token: json["token"],
role: json["role"],
);
Map<String, dynamic> toJson() => {
"doctorID": doctorId,
"nmCno": nmCno,
"doctorName": doctorName,
"contactNo": contactNo,
"username": username,
"emailID": emailId,
"strEmail": strEmail,
"id": id,
"intMobile": intMobile,
"gender": gender,
"currentAddress": currentAddress,
"depId": depId,
"entryDate": entryDate,
"password": password,
"code": code,
"isActive": isActive,
"hospitalName": hospitalName,
"department": department,
"deviceId": deviceId,
"profile": profile,
"token": token,
"role": role,
};
}
And this is where I need it to be displayed, where I have used FutureBuilder and I this I made a mistake here but not sure where exactly.
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: const Color.fromRGBO(249, 249, 249, 10),
body: Column(
children: [
Expanded(
child: Container(
height: 150.0,
width: 150.0,
color: Colors.grey.shade100,
child: FutureBuilder<DoctorResponseLoginModels>(
future: APIService().register(DoctorRequestLoginModels(
code: "code", username: "username", password: "password")),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
DoctorResponseLoginModels data = snapshot.data!;
return Column(
children: [
Text(data.doctorName!),
],
);
}
}
},
),
)),
],
));
}

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

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