Here is my code"
I've tried printing values.
I got value in token.
I'm able to iterate through the each value present in API using for each loop but data isn't storing into my model class.
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = prefs.getString("token") ?? null;
final userId = prefs.getInt("id") ?? null;
List<GroupListData> grpDataList = [];
if (token != null) {
String url = "${NetworkRequest.baseUrl}/api/group_list";
var groupRes = await http.post(Uri.parse(url), body: {
"user_id": '$userId'
}, headers: {
//'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
//print(groupRes.body);
if (groupRes.statusCode == 200) {
final rowJsonData = jsonDecode(groupRes.body);
GroupListData groupListData;
List<dynamic> groupLists = rowJsonData['data'];
groupLists.forEach((d) {
print(d['id']);
groupListData = GroupListData(
id: d['id'],
groupName: d["groupName"],
status: d["status"],
createdAt: d["createdAt"],
updatedAt: d["updatedAt"],
);
grpDataList.add(groupListData);
});
for (var d in rowJsonData['data']) {
print(d);
}
} else {
print('grpResp ${groupRes.statusCode}');
}
//print('Token : $token');
} else {
print('token is empty');
}
print(grpDataList);
return grpDataList;
}
here this is my JSON Data
{
"data": [
{
"id": 1,
"group_name": "payroll",
"status": 1,
"created_at": "2021-07-20 08:27:31",
"updated_at": "2021-07-20 10:09:11"
},
{
"id": 2,
"group_name": "New Recuritment",
"status": 1,
"created_at": "2021-07-20 11:21:40",
"updated_at": "2021-07-20 11:21:40"
}
],
"message": "Data Found",
"status": 200
}
here is my model class
i think that there is issue in my model class
i am not able to understand
class GroupListData {
GroupListData({
this.id,
this.groupName,
this.status,
this.createdAt,
this.updatedAt,
});
int? id;
String? groupName;
int? status;
DateTime? createdAt;
DateTime? updatedAt;
factory GroupListData.fromJson(Map<String, dynamic> json) => GroupListData(
id: json["id"],
groupName: json["group_name"],
status: json["status"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"group_name": groupName,
"status": status,
"created_at": createdAt!.toIso8601String(),
"updated_at": updatedAt!.toIso8601String(),
};
}
here is my ui code
FutureBuilder<List<GroupListData>>(
future: getGroupListData(),
builder: (BuildContext context,
AsyncSnapshot<List<GroupListData>> snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
),
);
}
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
return RoundedCard(
str: '${snapshot.data![index].groupName}', ///.groupName always return null value
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: FeedPage(feedTitle: 'Marketing Team'),
inheritTheme: true,
ctx: context),
);
print('Marketing card');
});
});
},
),
thanks in advance
You dont need to convert your json to modal by yourself.
if the Flutter SDK < 2.0 (Null safety) then please use this online json converter https://javiercbk.github.io/json_to_dart/
otherwise use this online json Converter for Flutter > 2.0 https://app.quicktype.io/
Related
what should I do to display this data
"result": [
{
"department_id": null,
"crime_time_id": "5562f55f-54aa-4e94-9f6c-9ce25d9e3fd9",
"village_id": "3174031001",
"cases": 3,
"villages": 3,
"target_id": null,
"department": null,
"crime_time": {
"id": "5562f55f-54aa-4e94-9f6c-9ce25d9e3fd9",
"name": "00.00 - 02.00"
},
"village": {
"id": "3174031001",
"name": "MAMPANG PRAPATAN"
}
},
{
"department_id": null,
"crime_time_id": "ca56d7a3-fdea-446a-a628-cc7091f314de",
"village_id": "1604082010",
"cases": 1,
"villages": 1,
"target_id": null,
"department": null,
"crime_time": {
"id": "ca56d7a3-fdea-446a-a628-cc7091f314de",
"name": "06.00 - 08.00"
},
"village": {
"id": "1604082010",
"name": "TANJUNG SIRIH"
}
}
]
I have try to handle this but there is some display error
'expected a value of type 'int?' but got one of type 'String' and
'the method fromjson isnt defined for the type data. try correcting the name to the name of an exsiting method
this my model:
class rangkumanKasus {
int? department_id;
String? crime_time_id;
int? village_id;
int? cases;
int? villages;
int? target_id;
String? department;
final Crime_Time crime_time;
final Village village;
rangkumanKasus({
this.department_id,
this.crime_time_id,
this.village_id,
this.cases,
this.villages,
this.target_id,
this.department,
required this.crime_time,
required this.village,
});
factory rangkumanKasus.fromJson(Map<String, dynamic> json) {
return rangkumanKasus(
department_id: json["department_id"],
crime_time_id: json['crime_time_id'],
village_id: json['village_id'],
cases: json['cases'],
villages: json['villages'],
target_id: json['target_id'],
department: json['department'],
crime_time: Crime_Time.fromJson(json['crime_time']),
village: Village.fromJson(json['village']),
);
}
}
class Crime_Time {
int? id;
String? name;
Crime_Time({
this.id,
this.name,
});
factory Crime_Time.fromJson(Map<dynamic, dynamic> json) {
return Crime_Time(
id: json['id'],
name: json['name'],
);
}
}
class Village {
int? id;
String? name;
Village({
this.id,
this.name,
});
factory Village.fromJson(Map<dynamic, dynamic> json) {
return Village(
id: json['id'],
name: json['name'],
);
}
}
and this how I try to display
Container(
child: FutureBuilder<List<rangkumanKasus>>(
future: listData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<rangkumanKasus> isiData = snapshot.data!;
return ListView.builder(
shrinkWrap: true,
itemCount: isiData.length,
itemBuilder: (context, index) {
return Container(
child: Text(
isiData[index].crime_time.name!,
style: TextStyle(color: Colors.red),
));
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const CircularProgressIndicator();
}),
When I start the project I got an unexpected null value.
I keep getting this error with this API, I don't have certain of what can be.
you can check here
api link: https://ffxivcollect.com/api/mounts/257
response
{
"id": 257,
"name": "Island Eggplant Knight",
"description": "Summon forth your island Eggplant Knight, an oversized vegetable embodiment of chivalry.",
"enhanced_description": "Hailing from the selfsame land as the Tomato King, the Eggplant Knight shared a crate with the sovereign when they were shipped out. However, he fell overboard when the vessel encountered rough seas, and drifted for days before being deposited on a desert island. Among other feats, he prides himself on having played a key role in the founding of the West Mandra Empire.",
"tooltip": "I thought ye were a feral turnip, a murderous eggplant, or summat like that! - Tiny Trader",
"movement": "Terrestrial",
"seats": 1,
"order": 240,
"order_group": 99,
"patch": "6.2",
"item_id": null,
"tradeable": false,
"owned": "3.9%",
"image": "https://ffxivcollect.com/images/mounts/large/257.png",
"icon": "https://ffxivcollect.com/images/mounts/small/257.png",
"bgm": "https://ffxivcollect.com/music/BGM_Ride_MJI.ogg",
"sources": [
{
"type": "Purchase",
"text": "12,000 Seafarer's Cowries",
"related_type": null,
"related_id": null
}
]
}
I'm using quick type to convert the JSON to dart and paste in the model only adding Required.
my home page:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(''),
),
body: ListView.builder(
itemCount: finalApi!.length,
itemBuilder: (context, index) {
return Container(
child: Text(finalApi![index].description),
);
},
),
);
}
}
url:
class RemoteService {
Future<List<FinalApi>> getPosts() async {
var client = http.Client();
var uri = Uri.parse('https://ffxivcollect.com/api/mounts/257');
var response = await client.get(uri);
if (response.statusCode == 200) {
var json = response.body;
return finalApiFromJson(json);
}
throw Text('aa');
}
}
my model:
List<FinalApi> finalApiFromJson(String str) =>
List<FinalApi>.from(json.decode(str).map((x) => FinalApi.fromJson(x)));
String finalApiToJson(List<FinalApi> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class FinalApi {
FinalApi({
required this.id,
required this.name,
required this.description,
required this.enhancedDescription,
required this.tooltip,
required this.movement,
required this.seats,
required this.order,
required this.orderGroup,
required this.patch,
required this.itemId,
required this.tradeable,
required this.owned,
required this.image,
required this.icon,
required this.bgm,
required this.sources,
});
int id;
String name;
String description;
String enhancedDescription;
String tooltip;
String movement;
int seats;
int order;
int orderGroup;
String patch;
dynamic itemId;
bool tradeable;
String owned;
String image;
String icon;
String bgm;
List<Source> sources;
factory FinalApi.fromJson(Map<String, dynamic> json) => FinalApi(
id: json["id"],
name: json["name"],
description: json["description"],
enhancedDescription: json["enhanced_description"],
tooltip: json["tooltip"],
movement: json["movement"],
seats: json["seats"],
order: json["order"],
orderGroup: json["order_group"],
patch: json["patch"],
itemId: json["item_id"],
tradeable: json["tradeable"],
owned: json["owned"],
image: json["image"],
icon: json["icon"],
bgm: json["bgm"],
sources:
List<Source>.from(json["sources"].map((x) => Source.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
"enhanced_description": enhancedDescription,
"tooltip": tooltip,
"movement": movement,
"seats": seats,
"order": order,
"order_group": orderGroup,
"patch": patch,
"item_id": itemId,
"tradeable": tradeable,
"owned": owned,
"image": image,
"icon": icon,
"bgm": bgm,
"sources": List<dynamic>.from(sources.map((x) => x.toJson())),
};
}
class Source {
Source({
required this.type,
required this.text,
required this.relatedType,
required this.relatedId,
});
String type;
String text;
dynamic relatedType;
dynamic relatedId;
factory Source.fromJson(Map<String, dynamic> json) => Source(
type: json["type"],
text: json["text"],
relatedType: json["related_type"],
relatedId: json["related_id"],
);
Map<String, dynamic> toJson() => {
"type": type,
"text": text,
"related_type": relatedType,
"related_id": relatedId,
};
}
Based on your response, It is returning a single item on map. Therefor the parser will be like
final data = FinalApi.fromJson(jsonDecode(json));
class RemoteService {
Future<List<FinalApi>> getPosts() async {
var client = http.Client();
var uri = Uri.parse('https://ffxivcollect.com/api/mounts/257');
var response = await client.get(uri);
try {
if (response.statusCode == 200) {
var json = response.body;
// finalApiFromJson(json);
final data = FinalApi.fromJson(jsonDecode(json));
return [data];
}
} catch (e) {
log(e.toString());
}
return [];
}
}
i'm trying to get media fields from the instagram api and i'm getting this error
type 'String' is not a subtype of type 'int' of 'index'
here's Homepage.dart :
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:insta_details/models/data.dart';
import 'package:insta_details/utils/custom_dio_mixin.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
static String id = "HomePage";
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with CustomDioMixin {
bool loading = true;
bool error = false;
late Media media;
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: loading
? const Center(
child: CircularProgressIndicator(),
)
: error
? const Center(
child: Text('An error has occurred!'),
)
: ListView.builder(
itemBuilder: (context, index) => MediaWidget(
media: media,
),
),
),
);
}
Future<void> getData() async {
try {
final storage = GetStorage();
final token = storage.read("accessToken");
Media? media;
final response = await dio.get(
'https://graph.instagram.com/me/media?fields=id,caption,media_url,timestamp&access_token=$token',
);
print("get data response => ${response.statusCode} ${response.data}");
Media mediadata = Media.fromJson(response.data);
print(mediadata);
} catch (e) {
print("get data failed");
print(e);
setState(() {
error = true;
});
} finally {
setState(() {
loading = false;
});
}
}
}
class MediaWidget extends StatelessWidget {
final Media media;
const MediaWidget({Key? key, required this.media}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: 6,
itemBuilder: (context, index) {
return Image.network(media.mediaUrl);
},
);
}
}
and here data.dart :
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
String id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Map<String, dynamic> toJson() => {
"id": id,
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}
and the log :
I/flutter ( 5699): get data response => 200 {data: [{id: 18106429915287733, caption: cabin in the woods, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=0omRv4cUGtwAX8bbmC7&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_fqBkL5ykJXWRj7Rcy4nCnyuXEKh-8o0TX9FJkJ4dcfQ&oe=61FD881A, timestamp: 2022-01-27T11:15:07+0000}, {id: 17917394609104775, caption: Truck, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX89PW0c&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_Qbj7zOH-UEzplA9mdIrCHaeb9EBBuz1RjKJclN9Q2RA&oe=61FE9898, timestamp: 2022-01-27T11:14:26+0000}, {id: 17921627228176014, caption: Gaara, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX9vOy4L&_nc_ht=scontent.cdninst
I/flutter ( 5699): get data failed
I/flutter ( 5699): type 'String' is not a subtype of type 'int' of 'index'
my JSON response :
{
"data": [
{
"id": "18106429915287733",
"caption": "cabin in the woods",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username": "parekchampl",
"timestamp": "2022-01-27T11:15:07+0000"
},
{
"id": "17917394609104775",
"caption": "Truck",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username": "parekchampl",
"timestamp": "2022-01-27T11:14:26+0000"
},
{
"id": "17921627228176014",
"caption": "Gaara",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX_SB6jL&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8rviJ6wbaT0yF1Hq2VprtnQ-W0rARS5oxIr52MIhC0Rw&oe=61FD720B",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:42+0000"
},
{
"id": "18024346318348836",
"caption": "Marceline",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272807293_686124672409566_4991399943515126026_n.jpg?_nc_cat=106&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=JMfTMSD_1c8AX-m5WDx&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_P38eDVtcqEYL053wGPkLjhHStLCh7_fgFnCg4LcH1yA&oe=61FD1F82",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:02+0000"
},
{
"id": "17859174368680579",
"caption": "uchiha shisui",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272721151_749467822692662_5191995429373550055_n.jpg?_nc_cat=111&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=01A68vtgY-kAX-ux6iB&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT9oWtK9VWV8j3c8Ij2YXctIpuh9sC-NJO1BLCwFObDDSA&oe=61FE0B03",
"username": "parekchampl",
"timestamp": "2022-01-27T11:12:35+0000"
},
{
"id": "17917757036265369",
"caption": "Son and Father",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660947_1107548556714461_1575953024252145708_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=Mzj5Wp9sv_oAX_2Z4Nv&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8Ywp3DUIemrIoCPajFvivfTG_-AWvEs2fpkngYXUN6Lg&oe=61FE17A1",
"username": "parekchampl",
"timestamp": "2022-01-27T11:11:47+0000"
}
],
"paging": {
"cursors": {
"before": "QVFIUnpEcERJTXdYRjd3SVp3MUo2U25UeWhhdlgxQ2xMY0diR2pYVFhCVl9TUUhlM1hqYllKWUpEWXJtYW5RWW41am1Lc3B4U281TU14ZAFoxSVBkMVRsZAkZAB",
"after": "QVFIUkgtUzExdDNsYzgwUFhGdnRXQlB6N0JkZATVFeU1DVkhzXzduLTF1RklpR1A5MDNMeWVEemtzdE15OVBlYmpYb29mQlVtdDJsX1N2SUcwa2ZAkc21jblZAn"
}
}
}
According to the documentation : https://developers.facebook.com/docs/instagram-basic-display-api/reference/media ,every field is a String
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Or change to something like below:
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.parse(json["data"]["id"] as String),
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: DateTime.parse(json["data"]["timestamp"] as String),
);
The value of your data key is a List not a Map. Here's an example:
const responseData =
{
"data":[
{
"id":"18106429915287733",
"caption":"cabin in the woods",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username":"parekchampl",
"timestamp":"2022-01-27T11:15:07+0000"
},
{
"id":"17917394609104775",
"caption":"Truck",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username":"parekchampl",
"timestamp":"2022-01-27T11:14:26+0000"
}
]
};
void main() {
final mediaList = responseData["data"]!.map((entry) => Media.fromJson(entry))
.toList();
for (var media in mediaList) {
print(media.id);
}
}
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
int? id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) {
return Media(
id: int.tryParse(json["id"]),
caption: json["caption"],
mediaUrl: json["media_url"],
timestamp: json["timestamp"],
);
}
Map<String, dynamic> toJson() => {
"id": id.toString(),
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}
On your model class id is nullable int, but you are receiving id as String.
You can typecast string to int On your Media.fromJson, while the id accept null value, if something wrong happen id will get null value.
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.tryParse(json["data"]["id"]),
And for toJson pass id as String
Map<String, dynamic> toJson() => {
"id": id.toString(),
More about int.tryParse.
HERE IS THE JSON OF RESPONSE BODY:
{
"status": "success",
"contents": [{
"id": "15",
"cname": "DOGS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "36",
"cat_id": "15",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}, {
"subcatid": "39",
"cat_id": "15",
"sub_category_name": "Beds",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}, {
"id": "14",
"cname": "CATS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "47",
"cat_id": "14",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}]
}
// API call to get the above json data:
Future<List<CatListData>> dashboardDataAPI(http.Client client) async {
final response = await client.get(Uri.parse(Utilities.BASE_URL));
List list = json.decode(response.body)['contents'];
return parsePhotos(list.toString());
}
// A function that converts a response body into a List
List<CatListData> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<CatListData>((json) => CatListData.fromJson(json)).toList();
}
// Cat List Class
class CatListData{
final String id;
final String cName;
final String dogImage;
final String catImage;
final List<SubCatListData> subCatListDataList;
CatListData({required this.id, required this.cName, required this.dogImage, required this.catImage, required this.subCatListDataList});
factory CatListData.fromJson(Map<String, dynamic> json) {
return CatListData(
id: json['id'] as String,
cName: json['cname'] as String,
dogImage: json['dogs_image'] as String,
catImage: json['cat_image'] as String,
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
);
}
}
// Sub Cat Class
class SubCatListData{
final String subCatId;
final String catId;
final String subCategoryName;
final String banner;
final String image;
SubCatListData({required this.subCatId, required this.catId, required this.subCategoryName, required this.banner, required this.image});
factory SubCatListData.fromJson(Map<String, dynamic> json) {
return SubCatListData(
subCatId: json['subcatid'] as String,
catId: json['cat_id'] as String,
subCategoryName: json['sub_category_name'] as String,
banner: json['banner'] as String,
image: json['image'] as String,
);
}
}
Here showing null when I print snapshot
Container(
child: FutureBuilder<List<CatListData>>(
future: dashboardDataAPI(http.Client()),
builder: (context, snapshot) {
print("Response:: "+snapshot.data.toString());
if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
}else if(snapshot.hasError){
return const Center(
child: Text('An error has occurred!'),);
}else{
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
)
Please let me know how I can fix this issue and parse the multiple json array data into the list.
Thanks
I believe the problem happens on this line on the CatListData.fromJson constructor:
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
you never call SubCatListData.fromJson, I believe this will work better for your assignment:
subCatListDataList: (json['sub_category'] as Iterable).map<SubCatListData>(
(value) => SubCatListData.fromJson(value as Map<String, dynamic>),
),
My JSON looks like this:
{
Info: [
{
c_type_id: "1",
cleaning type: "A Cleaning"
},
{
c_type_id: "2",
cleaning type: "B Cleaning"
},
{
c_type_id: "3",
cleaning type: "C Cleaning"
},
{
c_type_id: "4",
cleaning type: "D Cleaning"
},
{
c_type_id: "5",
cleaning type: "E Cleaning"
},
]
}
and here is the code:
The following code is created by this
Class 1:
class Album {
List<Info> info;
Album({this.info})
Album.fromJson(Map<String, dynamic> json) {
if (json['Info'] != null) {
info = List<Info>.empty();
json['Info'].forEach((v) {
info.add(new Info.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.info != null) {
data['Info'] = this.info.map((v) => v.toJson()).toList();
}
return data;
}
}
class 2:
class Info {
String cTypeId;
String cleaningType;
Info({this.cTypeId, this.cleaningType});
Info.fromJson(Map<String, dynamic> json) {
cTypeId = json['c_type_id'];
cleaningType = json['cleaning type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['c_type_id'] = this.cTypeId;
data['cleaning type'] = this.cleaningType;
return data;
}
}
This is the error I get when I execute the code:
error: The argument type 'List' can't be assigned to the parameter type 'String'.
Hoping for help!
You should Try below code your problem has been solved ->
Declare your API Call funtion
Future<List<dynamic>> getInfoData() async {
String url = 'https://fillmmaka.com/gigocleanapi/cleanintypes.php';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body)['Info'];
}
Declare your Widget
Center(
child: FutureBuilder<List<dynamic>>(
future: getInfoData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var id = snapshot.data[index]['c_type_id'];
var type = snapshot.data[index]['cleaning type'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(id),
title: Text(type),
),
);
},
),
);
}
return CircularProgressIndicator();
},
),
),
Your Screen look like this ->
What is your goal? What do you want to show on the screen?
For example, do you want to show a list with all the cleaning types?
You are getting this error because the attribute info in your Album class is a List:
class Album {
List<Info> info;
If you want to show the cleaningType of the first info on the list, you may do something like this:
return Text(snapshot.data.info[0].cleaningType);
Just keep in mind this will crash if the info list is empty.
you are trying to access the whole list there just use snapshot.data.info[index].variableName you want to access
and you will be good to go