I have a problem here, I'm trying to call the API and the response in the console shows the json response, but the screen shows an error like below,
Previously I managed to do it but when I tried to call it with a different API the result was not what I wanted.
Is there anyone here who can help me solve this problem.
Here I attach the code
the models I have
class KurikulumModel {
String? status;
String? code;
List<Data>? data;
KurikulumModel({status, code, data});
KurikulumModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
code = json['code'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['code'] = code;
if (data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? id;
String? name;
String? idSemester;
String? smt;
String? idProdi;
String? prodi;
String? createdAt;
String? updatedAt;
String? createdBy;
String? updatedBy;
int? jumlahSksWajib;
int? jumlahSksPilihan;
int? jumlahSksSertifikat;
int? status;
int? stsHapus;
Data(
{id,
name,
idSemester,
smt,
idProdi,
prodi,
createdAt,
updatedAt,
createdBy,
updatedBy,
jumlahSksWajib,
jumlahSksPilihan,
jumlahSksSertifikat,
status,
stsHapus});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
idSemester = json['id_semester'];
smt = json['smt'];
idProdi = json['id_prodi'];
prodi = json['prodi'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
createdBy = json['created_by'];
updatedBy = json['updated_by'];
jumlahSksWajib = json['jumlah_sks_wajib'];
jumlahSksPilihan = json['jumlah_sks_pilihan'];
jumlahSksSertifikat = json['jumlah_sks_sertifikat'];
status = json['status'];
stsHapus = json['sts_hapus'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['name'] = name;
data['id_semester'] = idSemester;
data['smt'] = smt;
data['id_prodi'] = idProdi;
data['prodi'] = prodi;
data['created_at'] = createdAt;
data['updated_at'] = updatedAt;
data['created_by'] = createdBy;
data['updated_by'] = updatedBy;
data['jumlah_sks_wajib'] = jumlahSksWajib;
data['jumlah_sks_pilihan'] = jumlahSksPilihan;
data['jumlah_sks_sertifikat'] = jumlahSksSertifikat;
data['status'] = status;
data['sts_hapus'] = stsHapus;
return data;
}
}
then i call
class KurikulumProvider extends ChangeNotifier {
Future<Data> getKurikulum() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/kurikulum',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return Data.fromJson(jsonDecode(response.body));
} else {
throw Exception('Token Expired!');
}
}
}
and this is when i want to call it in API
...
FutureBuilder<Data>(
future: kurikulumProvider.getKurikulum(),
builder: (context, snapshot) {
return Table(
border: TableBorder.all(color: Colors.grey),
children: [
TableRow(children: [
Column(children: [
Text('Nama Kurikulum', style: bold6)
]),
Column(children: [
Text('Program Studi', style: bold6)
]),
Column(children: [
Text('Masa Berlaku', style: bold6)
]),
]),
TableRow(
children: [
Column(children: [
Text(snapshot.data!.name.toString(),
style: regular6,
textAlign: TextAlign.center)
]), ...
the future is not completed yet but u already return the table modle.
you can listen to the snapshot is it already has data or not yet.
try changes your code like this
FutureBuilder<T>(
future: future,
builder: (
BuildContext context,
AsyncSnapshot<String> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
//return something
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
//return error
} else if (snapshot.hasData) {
//return your table
} else {
//return empty data
}
} else {
//connection error return
}
},
),
i suggest to use any state management to handle this. provider/bloc to handle of the data.
Related
I am trying to fetch image from an api. For that I am using http package for flutter. I created Model View Controller pattern to arrange the structure of the project. Here is the api link and response:
https://wrestlingworld.co/wp-json/wp/v2/posts/128354
Response =>
[{"id":128640,"date":"2022-11-04T15:09:58","date_gmt":"2022-11-04T09:39:58","guid":{"rendered":"https:\/\/wrestlingworld.co\/?p=128640"},"modified":"2022-11-04T15:10:04","modified_gmt":"2022-11-04T09:40:04","slug":"impact-knockouts-tag-team-championship-match-announced-for-over-drive-2022","status":"publish","type":"post","link":"https:\/\/wrestlingworld.co\/news\/impact-knockouts-tag-team-championship-match-announced-for-over-drive-2022","title":{"rendered":"Impact Knockouts Tag Team Championship Match Announced for Over Drive"},"content":{"rendered":"\n<p>Impact Knockouts Tag Team Championships will be on the line at Over Drive on November 18th. It has <a href=\"https:\/\/impactwrestling.com\/2022\/11\/03\/tasha-steelz-savannah-evans-look-to-topple-the-death-dollz-in-knockouts-world-tag-team-title-showdown-at-over-drive\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">been announced<\/a> that Death Dollz (Taya Valkyrie and Jessicka) will be defending their titles against Tasha Steelz and Savannah
Here is my model:
class NewsModel {
int? id;
String? date;
String? slug;
String? status;
Title? title;
Title? content;
List<OgImage>? ogImage;
int? author;
NewsModel(
{this.id,
this.date,
this.slug,
this.status,
this.title,
this.content,
this.ogImage,
this.author});
NewsModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
date = json['date'];
slug = json['slug'];
status = json['status'];
title = json['title'] != null ? new Title.fromJson(json['title']) : null;
content =
json['content'] != null ? new Title.fromJson(json['content']) : null;
if (json['og_image'] != null) {
ogImage = <OgImage>[];
json['og_image'].forEach((v) {
ogImage!.add(new OgImage.fromJson(v));
});
}
author = json['author'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['date'] = this.date;
data['slug'] = this.slug;
data['status'] = this.status;
if (this.title != null) {
data['title'] = this.title!.toJson();
}
if (this.content != null) {
data['content'] = this.content!.toJson();
}
if (this.ogImage != null) {
data['og_image'] = this.ogImage!.map((v) => v.toJson()).toList();
}
data['author'] = this.author;
return data;
}
}
class Title {
String? rendered;
Title({this.rendered});
Title.fromJson(Map<String, dynamic> json) {
rendered = json['rendered'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['rendered'] = this.rendered;
return data;
}
}
class OgImage {
String? url;
OgImage({this.url});
OgImage.fromJson(Map<String, dynamic> json) {
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
return data;
}
}
Here you can see OgImage is a list So I created a card and tried this code:
final int id;
final String title;
final String description;
final List<dynamic> img;
const NewsCard({
required this.id,
required this.title,
required this.description,
required this.img,
});
ListView.builder(
itemCount: img.length,
itemBuilder: (context, item){
return Image.network(
img[item],
height: 120,
width: double.infinity
);
},
),
Here is the front end code where I am passing value :
Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: allNews.length,
itemBuilder: (context, i) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: NewsCard(
id: allNews[i].id as int,
title: allNews[i].title!.rendered!,
description: allNews[i].content!.rendered!,
img: allNews[i].ogImage?[0].url as List<dynamic>,
),
);
}),),
Here is my controller :
Future<bool> getNews() async {
var url = Uri.parse(urlnews);
// var token = storage.getItem('token');
try {
http.Response response = await http.get(url);
print(response.body);
var data = json.decode(response.body) as List;
// print(data);
List<NewsModel> temp = [];
data.forEach((element) {
NewsModel product = NewsModel.fromJson(element);
temp.add(product);
});
_news = temp;
notifyListeners();
return true;
} catch (e) {
print(e);
return false;
}
}
List<NewsModel> get allNews {
return [..._news];
}
This code has errors I mentioned in the title already. Here I have a qustion like how can I pass list value inside the card. What is right way to fetch lists of image inside a widget.
There are a few issues with your code:
1. In your NewsModel class file, you're mapping it all wrong.
You're mapping json['og_image'] to a List, while json['og_image'] doesn't exist in the first place. If you see the JSON response, instead it's within the json['yoast_head_json'] key. So, instead of json['og_image'] you need to do json['yoast_head_json']['og_image'].
Change:
if (json['og_image'] != null) {
ogImage = <OgImage>[];
json['og_image'].forEach((v) {
ogImage!.add(new OgImage.fromJson(v));
});
}
to:
if (json['yoast_head_json'] != null &&
json['yoast_head_json']['og_image'] != null) {
ogImage = <OgImage>[];
json['yoast_head_json']['og_image'].forEach((v) {
ogImage!.add(OgImage.fromJson(v));
});
2. In your frontend part, you're trying to cast a nullable type of list allNews[i].ogImage?[0].url as List<dynamic> to List<dynamic>, which will throw exception in case the list is NULL which is in your case.
so, instead of:
img: allNews[i].ogImage?[0].url as List<dynamic>
do:
img: allNews[i].ogImage ?? []
3. Finally, in your NewsCard class:
Change:
Image.network(
img[item],
...
);
to
Image.network(
img[item].url,
...
);
Enjoy :)
I have Categories, and each category contains multiple and different subcategories.
I passed the Id of Categories to the other screen.
First Screen:
onTap: (() => Get.to(const CategoryDetails(), arguments: {
"id":" ${categoriesController.cat!.elementAt(i).sId.toString()} ", })),
ArgumentController
import 'package:get/get.dart';
class ArgumentController extends GetxController {
String? id;
#override
void onInit() {
id = Get.arguments['id'];
super.onInit();
}
}
View File
class _CategoryDetailsState extends State<CategoryDetails> {
int selectedCategoryIndex = 0;
CategoriesController categoriesController = Get.put(CategoriesController());
#override
void initState() {
super.initState();
categoriesController.getCategoriesFromApi();
}
#override
Widget build(BuildContext context) {
ArgumentController controller = Get.put(ArgumentController());
debugPrint(controller.id);
return Scaffold(
appBar: AppBar(
title: const Text("Category Details"),
),
body: Column(
children: [
Text("${controller.id}"),
const Text("data"),
ListView.builder(itemBuilder: (context, index) {
return Column(
children: [
Text(categoriesController.cat!
.elementAt(index)
.subcategories!
.elementAt(selectedCategoryIndex)
.name
.toString()),
],
);
})
],
),
);
}
}
Controller file:
import 'dart:convert';
import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../model/categoriesmodel.dart' as categories_model;
class CategoriesController extends GetxController {
Iterable<categories_model.Response>? cat;
var isDataLoading = false.obs;
getCategoriesFromApi() async {
try {
isDataLoading(true);
http.Response response = await http.post(
Uri.tryParse('-----')!,
headers: {
HttpHeaders.authorizationHeader: '-------',
});
if (response.statusCode == 200) {
var result = jsonDecode(response.body);
cat = categories_model.Categories.fromJson(result).response;
} else {}
} catch (e) {
debugPrint("Error while getting Data $e");
} finally {
isDataLoading(false);
}
}
}
Categoriesmodel file
class Categories {
String? status;
List<Response>? response;
Categories({this.status, this.response});
Categories.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['response'] != null) {
response = <Response>[];
json['response'].forEach((v) {
response!.add(Response.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
if (response != null) {
data['response'] = response!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Response {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
String? icon;
String? logo;
int? itemsCount;
String? lang;
List<Subcategories>? subcategories;
Response(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.icon,
this.logo,
this.itemsCount,
this.lang,
this.subcategories});
Response.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
icon = json['icon'];
logo = json['logo'];
itemsCount = json['itemsCount'];
lang = json['lang'];
if (json['subcategories'] != null) {
subcategories = <Subcategories>[];
json['subcategories'].forEach((v) {
subcategories!.add(Subcategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['icon'] = icon;
data['logo'] = logo;
data['itemsCount'] = itemsCount;
data['lang'] = lang;
if (subcategories != null) {
data['subcategories'] =
subcategories!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Subcategories {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
int? itemsCount;
String? lang;
Subcategories(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.itemsCount,
this.lang});
Subcategories.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
itemsCount = json['itemsCount'];
lang = json['lang'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['itemsCount'] = itemsCount;
data['lang'] = lang;
return data;
}
}
The problem is in selectedCategoryIndex, how to express that
selectedCategoryIndex == categoriesController.Where((element) => element.sid == the argument passed);
note that it's not acceptable categoriesController.Where..
I just assumed your question to be what I think and posting this solution.
selectedCategoryIndex ==
categoriesController.cat.singleWhere((element) => element.id == id).sId;
It's say Expected an identifier. In the late final groupId2 = GroupModel.fromDocumentSnapshot(doc: );
I don't what to put inside it. I am New to to flutter
The Screen:
late final groupId2 = GroupModel.fromDocumentSnapshot(doc: //Expected an identifier HERE);
This is the groupModel:
factory GroupModel.fromDocumentSnapshot({required DocumentSnapshot doc}) {
return GroupModel(
id: doc.id,
name: (doc.data() as Map<String, dynamic>)["name"],
leader: (doc.data() as Map<String, dynamic>)["leader"],
members: List<String>.from((doc.data() as Map<String, dynamic>)["members"]),
groupCreate: (doc.data() as Map<String, dynamic>)["groupCreate"],
);
}
Here is the model I created before. I hope it is helpful for you.
class ProductModel {
static const ID = "id";
static const IMAGE = "image";
static const NAME = "name";
static const BRAND = "brand";
static const PRICE = "price";
String? id;
String? image;
String? name;
String? brand;
int? price;
ProductModel(
{required this.id,
required this.image,
required this.name,
required this.brand,
required this.price});
factory ProductModel.fromFire(QueryDocumentSnapshot snapshot) {
return ProductModel.fromMap(snapshot as Map<String, dynamic>);
}
factory ProductModel.fromDocumentSnapshot({required DocumentSnapshot<Map<String,dynamic>> doc}){
// print(doc.data()!["id"]);
// print(doc.data()!["image"]);
// print(doc.data()!["name"]);
// print(doc.data()!["brand"]);
// print(doc.data()!["price"]);
return ProductModel(
id: doc.data()!["id"],
image: doc.data()!["image"],
name: doc.data()!["name"],
brand: doc.data()!["brand"],
price: doc.data()!["price"],
);
}
Map<String, dynamic> toJson() => {
'id': id,
'image': image,
'name': name,
'brand': brand,
'price': price,
};
ProductModel.fromMap(Map<String, dynamic> data) {
id = data[ID];
image = data[IMAGE];
name = data[NAME];
brand = data[BRAND];
price = data[PRICE];
}
}
Source Code: defining function
Future<void> getMessagesTestTest() async{
var aa = await _firestore.collection('ProductModel').snapshots().map((notes){
notesFromFirestore.clear();
for(final DocumentSnapshot<Map<String,dynamic>> doc in notes.docs){
log("start in loop");
log('doc.id == ${doc.id}');
// print("start in loop");
// print('doc.id == ${doc.id}');
notesFromFirestore.add(ProductModel.fromDocumentSnapshot(doc:doc));
// print(ProductModel.fromDocumentSnapshot(doc:doc));
}
// print(notesFromFirestore.first.id.toString());
return notesFromFirestore;});
// int count = await allData.length;
aa.listen(
(event) => print("Data Retrieved"),
);
// print(aa.length);
print( 'List Size = ${notesFromFirestore.length}');
var count = 0;
for (final ProductModel notesFromFirestoreA in notesFromFirestore) {
count++;
print('Loop Counter == ${count}');
print('Id == ${notesFromFirestoreA.id}');
print('Name == ${notesFromFirestoreA.name}');
print('Price == ${notesFromFirestoreA.price}');
print('Brand == ${notesFromFirestoreA.brand}');
print('image == ${notesFromFirestoreA.image}');
}
}
This is my model class and I am trying to get all the data but getting error and don't know why.
HomePageModel homePageModelFromJson(String str) => HomePageModel.fromJson(json.decode(str));
String homePageModelToJson(HomePageModel data) => json.encode(data.toJson());
class HomePageModel with ChangeNotifier {
HomePageModel({
this.data,
});
List<Datum>? data;
factory HomePageModel.fromJson(Map<String, dynamic> json) => HomePageModel(
data: List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
schoolid: json["schoolid"],
name: json["name"],
logo: json["logo"],
address: json["address"],
contact: json["contact"],
principalname: json["principalname"],
principalcontact: json["principalcontact"],
slogan: json["slogan"],
webAddress: json["web_address"] == null ? null : json["web_address"],
description: json["description"] == null ? null : json["description"],
email: json["email"],
pan: json["pan"],
establishedYear: json["established_year"],
);
Map<String, dynamic> toJson() => {
"schoolid": schoolid,
"name": name,
"logo": logo,
"address": address,
"contact": contact,
"principalname": principalname,
"principalcontact": principalcontact,
"slogan": slogan,
"web_address": webAddress == null ? null : webAddress,
"description": description == null ? null : description,
"email": email,
"pan": pan,
"established_year": establishedYear,
};
}
This is how I am trying to fetch data:
class HomePageModels with ChangeNotifier{
List<HomePageModel> _hItem = [];
List<HomePageModel> get hItem{
return [..._hItem];
}
Future<void> getHomeData(BuildContext context) async{
const url = "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try{
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
List<HomePageModel> loadedHomeData = [];
if(extractedData == null){
return;
}
if(response.statusCode == 200){
print(extractedData);
}
extractedData.forEach((element){
loadedHomeData.add(HomePageModel.fromJson(element));
});
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
}catch(e){
rethrow;
}
}
}
But I am getting error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
The problem is the way you are trying to parse the data, you don't need to loop over every element to parse it, in your model just make it return a list type like this,
class HomePageModel with ChangeNotifier {
List<Datum>? data;
HomePageModel({this.data});
HomePageModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Datum>[];
json['data'].forEach((v) {
data!.add(new Datum.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
Datum.fromJson(Map<String, dynamic> json) {
schoolid = json["schoolid"];
name = json["name"];
logo = json["logo"];
address = json["address"];
contact = json["contact"];
principalname = json["principalname"];
principalcontact = json["principalcontact"];
slogan = json["slogan"];
webAddress = json["web_address"];
description = json["description"];
email = json["email"];
pan = json["pan"];
establishedYear = json["established_year"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['schoolid'] = this.schoolid;
data['name'] = this.name;
data['logo'] = this.logo;
data['address'] = this.address;
data['contact'] = this.contact;
data['principalname'] = this.principalname;
data['principalcontact'] = this.principalcontact;
data['slogan'] = this.slogan;
data['web_address'] = this.webAddress;
data['description'] = this.description;
data['email'] = this.email;
data['pan'] = this.pan;
data['established_year'] = this.establishedYear;
return data;
}
}
and in your view model you can just parse the extracted data from response.body like this,
class HomePageModels with ChangeNotifier {
HomePageModel? _hItem;
HomePageModel get hItem {
return _hItem!;
}
Future<void> getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-
4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
if (extractedData == null) {
return;
}
if (response.statusCode == 200) {
print(extractedData);
}
HomePageModel loadedHomeData =
HomePageModel.fromJson(extractedData);
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
} catch (e) {
rethrow;
}
}
}
getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final extractedData = json.decode(response.body);
List loadedHomeData = extractedData;
_hItem = loadedHomeData.map((e) => HomePageModel.fromJson(e)).toList();
}
notifyListeners();
return _hItem;
} catch (e) {
rethrow;
}
}
I am trying to show data to listview but it doesn't show anything.there is json below ,am i doing something wrong,i tired to print the data in api call but i can print the data but not in the listview,
i having hardtime to understand what i doing wrong or correct.please help me on this
if (response.statusCode == 200) {
try {
if (status == true) {
var company_list = value['doc'];
for (int i = 0; i < company_list.length; i++) {
print(company_list);
var mobile_list = company_list["mobile"];
var email_list = company_list["email"];
company_model.add(CompanyModel.fromJson(company_list,mobile_list,email_list));
}
setState(() {
print("UI Updated");
});
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
e.toString();
}
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
Json
{
"status":true,
"doc":{
"mobile":[
"9961256754",
"8974525672"
],
"email":[
],
"_id":"5f3a0dfe88b9d50453e92133",
"name":"MRC Labour",
"terms":{
"english":"We Shall not be liable for any disputes arising between the users and the
labourers",
"malayalam":"We Shall not be liable for any disputes arising between the users and the
labourers"
}
}
}
Model
class CompanyModel {
String id = "";
String mobile = "";
String email = "";
String name = "";
String english = "";
String malayalam = "";
CompanyModel({this.id, this.mobile, this.email, this.name, this.english,this.malayalam});
CompanyModel.fromJson(json,mobile_list,email_list)
: id = json['_id'].toString(),
mobile = mobile_list,
email = email_list,
name = json['name'].toString(),
english = json['terms']['english'].toString(),
malayalam = json['terms']['malayalam'].toString();
}
When the debugger hit at this line it breaks without any errors company_model.add(CompanyModel.fromJson(data,mobile_list,email_list));
This is listview code
Container(
height: 80,
width: 100,
color: Colors.blueGrey[100],
padding: EdgeInsets.all(10),
child: ListView.separated(
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
itemCount: company_model.length,
itemBuilder: (BuildContext context, int index) {
CompanyModel data = company_model[index];
print(data);
return Container(
height: 10,
color: Colors.green,
child: Text(data.name.toString(),style: TextStyle(color: Colors.black),),
);
},
),
),
First of all, your model is wrong, you're parsing a List (mobile and email) as a String in your model, also, you don't really need to pass 2 additional parameters to the function.
class CompanyModel {
List<String> mobile;
List<String> email;
String sId;
String name;
Terms terms;
CompanyModel({this.mobile, this.email, this.sId, this.name, this.terms});
CompanyModel.fromJson(Map<String, dynamic> json) {
mobile = json['mobile'].cast<String>();
email = json['email'].cast<String>();
sId = json['_id'];
name = json['name'];
terms = json['terms'] != null ? new Terms.fromJson(json['terms']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['mobile'] = this.mobile;
data['email'] = this.email;
data['_id'] = this.sId;
data['name'] = this.name;
if (this.terms != null) {
data['terms'] = this.terms.toJson();
}
return data;
}
}
class Terms {
String english;
String malayalam;
Terms({this.english, this.malayalam});
Terms.fromJson(Map<String, dynamic> json) {
english = json['english'];
malayalam = json['malayalam'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['english'] = this.english;
data['malayalam'] = this.malayalam;
return data;
}
}
Also, double check that you're initializing the company_model as something like: List company_model = [] otherwise it initialize as null and won't work the rest of your code.
if (response.statusCode == 200) {
try {
if (status == true) {
var company_json = value['doc'];
company_model.add(CompanyModel.fromJson(company_json));
setState(() {
print("UI Updated");
});
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
e.toString();
}
} else {
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
The best way to create model is in the link below
https://app.quicktype.io/
just put your json on as input on left side and select dart as language from left, you are good to go.