How to pick and show particular values from json with dart (flutter)? - json

I am an absolute beginner and would appreciate your help very much.
My json is as follows:
[
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity",
"val": 73,
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature",
"val": 16.8,
"ts": 1661671736782,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition",
"val": "CLEAR",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime",
"val": "DAY",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection",
"val": 10,
"ts": 1661671736784,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed",
"val": 18.503999999999998,
"ts": 1661671736784,
"ack": true
}
]
When I want to pick and show a particular value, e.g. for humidity, I get the following error:
type 'String' is not a subtype of 'int' of 'index'
My dart-code is as follows:
class EinzelwerteList {
final List<Wetter> einzelwerte;
EinzelwerteList({
required this.einzelwerte,
});
factory EinzelwerteList.fromJson(List<dynamic> parsedJson) {
List<Wetter> einzelwerte = <Wetter>[];
einzelwerte = parsedJson.map((i) => Wetter.fromJson(i)).toList();
return new EinzelwerteList(einzelwerte: einzelwerte);
}
}
class Wetter {
final String id;
final Int val;
final Int ts;
final Bool ack;
Wetter({
required this.id,
required this.val,
required this.ts,
required this.ack,
});
factory Wetter.fromJson(Map<String, dynamic> json) {
return Wetter(
id: json['id'].toString(),
val: json['val'],
ts: json['ts'],
ack: json['ack']);
}
}
Future<Wetter> fetchWetter() async {
final response = await http.get(Uri.parse(
'http://192.168.178.37:8087/getBulk/hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
debugPrint(humidity);
return Wetter.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Wetter');
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Wetter> futureWetter;
#override
void initState() {
super.initState();
futureWetter = fetchWetter();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.green,
//scaffoldBackgroundColor:
),
home: Scaffold(
appBar: AppBar(
title: const Text('Micha lernt Flutter & Dart'),
),
body: Center(
child: FutureBuilder<Wetter>(
future: futureWetter,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.val.toString());
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Container();
},
),
),
),
);
}
}
What do I do wrong?
As I said I am a total newbie and try to learn. So please be patient even if I ask dumb question.
Best regards.

There are multiple problems but the specific problem you are getting right now is the following piece of code:
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
The JSON does not contain a Map as the first level but instead a List. So you are getting an error since a List expects an int inside the [] while you are providing a String.
Another problem, you are going to have later, is that you are using the wrong types in your Wetter class. The types Int and Bool comes from dart:ffi and is meant to be used if you are integrating with native C code.
You should instead use int and bool.
A third problem is that val in your JSON contains a mix of types. So in your example you can see it is sometimes double and other times int and sometime String... the mix of int and double can be solved by use the num type but you need to add some custom handling for the String.

Related

How can i pass this complex Json MAP Data into flutter Listview

i am new to flutter, and i meet this API with complex "MAP" json. What i want is to display the list of countries with their details in flutter listview, How can i achieve that? Most of answers explain about "LIST" json.
{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
{
"id": "1",
"attributes": {
"name": "Grenada",
"code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
},
{
"id": "2",
"attributes": {
"name": "Malaysia",
"code": "MY",
"subregion": "South-Eastern Asia",
"flag": "https://flagcdn.com/my.svg",
"postalcode": "^(\\d{5})$",
"latitude": "2.5",
"longitude": "112.5",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
}
]
}
}
I found this GitHub project with these files json, modelClass Mainclass which relate with the concept but mine is has got one extra braces (map) so i do not know how to achieve the goal.
if there any suggestion or best way to code please help me.
this is how they created in model class but, but it does not work with me.
class Product {
final List<Result> results;
Product({this.results});
factory Product.fromJson(Map<String, dynamic> data) {
var list = data['data']['result'] as List;
List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
return Product(
results: resultList,
);
}
}
what i have done is
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var data_from_link;
getData() async {
final String link = 'myurl';
data_from_link = await http.get(Uri.parse(link), headers: {"Accept": "application/json"});
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
return ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
)
);
}
}
You can create two classes for Country and Attribute
class Country {
const Country({required this.id, required this.attributes});
/// Creates a Country from Json map
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json['id'] as String,
attribute:
Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
);
/// A description for id
final String id;
final Attribute attributes;
}
class Attribute {
const Attribute({
required this.name,
required this.code,
required this.createdAt,
required this.updatedAt,
});
/// Creates a Attribute from Json map
factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
name: json['name'] as String,
code: json['code'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
);
final String name;
final String code;
final DateTime createdAt;
final DateTime updatedAt;
}
when decoding:
final res = jsonDecode(json) as Map<String, dynamic>;
final List<Country> list = (res['data']['countries'] as
List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
Thank you but how can i print or call data from country attribute
after decoding because when i try something like Print
(list.country.attribute.name) . I fail. My goal is to display on
Listview
You can use it like this:
ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list[i].attributes.name,
),
subtitle: Text(list[i].attributes.code),
)),
UPDATE
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<List<Country>> futureList;
Future<List<Country>?> getData() async {
final String link = 'yoururl';
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final List<Country> list = (res['data']['countries'] as List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
return list;
} else {
throw Exception('Failed to fetch data');
}
}
#override
void initState() {
super.initState();
futureList = getData();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureList,
builder: (context, snapshot) {
if (snapshot.hasData) {
final list = snapshot.data;
return ListView.builder(
itemCount: list!.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
),
);
} else if (snapshot.hasError) {
return const Text('error fetching data');
}
return const CircularProgressIndicator();
},
);
}
}

Stuck with json in flutter

I dont know the problem is because when debuging there isn't error info but the value of json is empty when I print info.lenght
class _HomePageState extends State<HomePage> {
List info = [];
_initData(){
DefaultAssetBundle.of(context).loadString("json/info.json").then((value){
info = jsonDecode(value);
});
}
#override
void iniState(){
super.initState();
_initData();
}
and below is my json code in json/info.json
[
{
"title": "Glue",
"img": "assets/ex1.png"
},
{
"title": "Abs",
"img": "assets/ex2.png"
},
{
"title": "Legs",
"img": "assets/ex3.png"
},
{
"title": "Arms",
"img": "assets/ex4.png"
}
]
and how to we print the img and title value of json in dart?
You have to first create a model class for your json response.
// To parse this JSON data, do
//
// final jsonModel = jsonModelFromJson(jsonString);
import 'dart:convert';
List<JsonModel> jsonModelFromJson(String str) => List<JsonModel>.from(json.decode(str).map((x) => JsonModel.fromJson(x)));
String jsonModelToJson(List<JsonModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class JsonModel {
JsonModel({
this.title,
this.img,
});
String title;
String img;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
title: json["title"] == null ? null : json["title"],
img: json["img"] == null ? null : json["img"],
);
Map<String, dynamic> toJson() => {
"title": title == null ? null : title,
"img": img == null ? null : img,
};
}
then just use this model class to decode your json file.
var result = JsonModel.fromJson(jsonResponse);
Later, you can just use
result.title or result.img to get the data
You have to add your json file into pubspec.yaml file.
flutter:
assets:
- json/info.json
Before loading page view, you should load values from your json file and assign a list in initState. After that, you can use list as map by [index][header].
class JsonResult extends StatefulWidget {
const JsonResult({Key? key}) : super(key: key);
#override
_JsonResultState createState() => _JsonResultState();
}
class _JsonResultState extends State<JsonResult> {
var jsonList = [];
#override
void initState() {
rootBundle.loadString("json/info.json").then((value) {
jsonList = json.decode(value);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListView.builder(
itemBuilder: (context, index) {
return ListTile(
leading: Image.asset(jsonList[index]["img"]),
title: Text(jsonList[index]["title"]),
);
},
itemCount: jsonList.length,
),
),
);
}
}

type 'String' is not a subtype of type 'int' of 'index' while getting media fields using the instagram API

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.

How to implement listview from nested json data using http request in flutter?

I am new in flutter. i want to using http request for nested json data and want to show that data in listview. i made http request for get data. and i got 200. but problem is how to return my response for nested json data and show these data to listview? i read many documents but not properly understood. can anyone teach me how to implement this and if i made any wrong, what kind of wrong?
from json i also want to show "count", "idEmployee", "fullname" in my listview.
N.B: this api and token is just for test purpose.
Nested Json Data
{
"success": true,
"data": {
"count": 261,
"data": [
{
"idEmployee": 3588,
"avatar": null,
"fullName": "Moodle Connection Test",
"officeID": "1003588",
"email": "",
"designation": "Senior Executive",
"department": "Accounts",
"mobileNumber": "",
"workStation": "Work Station 12",
"businessUnit": "CDA"
}
],
}
}
ListAlbum Model Class
class ListAlbum {
final int? idEmployee;
final String? avatar;
final String? fullName;
final String? officeID;
final String? email;
final String? designation;
final String? department;
final String? mobileNumber;
final String? workStation;
final String? businessUnit;
ListAlbum({
this.idEmployee,
this.avatar,
this.fullName,
this.officeID,
this.email,
this.designation,
this.department,
this.mobileNumber,
this.workStation,
this.businessUnit,
});
factory ListAlbum.fromJson(Map<String, dynamic> json) {
return ListAlbum(
idEmployee: json['idEmployee'],
avatar: json['avatar'],
fullName: json['fullName'],
officeID: json['officeID'],
email: json['email'],
designation: json['designation'],
department: json['department'],
mobileNumber: json['mobileNumber'],
workStation: json['workStation'],
businessUnit: json['businessUnit'],
);
}
}
Api Calling
Future<List<ListAlbum>> listData() async {
final response = await http.post(
Uri.parse('https://portal-api.jomakhata.com/api/getOrganizationData'),
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
'Authorization':
'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo',
},
body: jsonEncode(<String, String>{
'limit': 5.toString(),
'orderBy': 'idEmployee',
'orderType': 'DESC'
}),
);
if (response.statusCode == 200) {
print(response.statusCode);
print("ok");
print(response.body);
return // here how to return for nested json data?
} else {
throw Exception('Failed to create album.');
}
}
List View
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
late Future<List<ListAlbum>> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = listData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Create Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: FutureBuilder<List<ListAlbum>>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final ListAlbum item = snapshot.data![index];
return ListTile(
title: Text(item.fullName!),
subtitle: Text(item.designation!),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
Ok, first of all, I sure hope this line :
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo
Is not actually your authentication credentials because it would take very little effort to decode that, and it would compromise your entire application.
Now, regarding your question, I might be wrong, but if I recall correctly, the http package will return a JSON response as a String, so first things first convert it to json using:
Map<String, dynamic> json = jsonDecode(response.data);
Then you can use a map method to return the models:
return json['data']['data'].map<ListAlbum>((value) => ListAlbum.fromJson(value));
Haven't tested it, but I believe that should work.

how to get complex json data in future builder dart

{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"id": 6,
"title": "Java6",
"description": "Java Basic",
"category": {
"id": 1,
"name": "Math"
},
"sub_category": {
"id": 4,
"name": "Test"
},
"tag": "string",
"video": {
"id": 6,
"duration": 10,
"thumbnail": "https://ibb.co/MZkfS7Q",
"link": "https://youtu.be/RgMeVbPbn-Q",
"views": 0
},
"quiz": {
"mcq": [
{
"id": 6,
"question": "q",
"option1": "b",
"option2": "c",
"option3": "d",
"option4": "e",
"answer": 1,
"appears_at": 0
}
]
},
"avg_rating": 1,
"total_number_of_rating": 1
},]}
how can I show this JSON data in future builder in dart
I have tried this way
Future<dynamic> geteducators() async {
String serviceurl = "https://api.spiro.study/latest-videos";
var response = await http.get(serviceurl);
final jsonrespose = json.decode(response.body);
print('title: ${jsonrespose}');
Videos latestVideo = Videos.fromJson(jsonrespose);
return latestVideo.results;
}
#override
void initState() {
super.initState();
_futureeducators = geteducators();
}
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://dog.ceo/api/breeds/image/random'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
//final int userId;
final String message;
final String status;
// final String region;
// final String country;
// final String title;
Album({
//required this.userId,
required this.message,
required this.status,
// required this.country,
// required this.region,
//required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
// userId: json['userId'],
message: json['message'],
status: json['status'],
// country: json['country'],
// region: json['region'],
//title: json['total'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data!.status),
Image(image: NetworkImage(snapshot.data!.message))
],
); //Text(snapshot.data!.ip);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
//in this way you can get json data and show it in grid or list view.
How to use nested future builder for complex json i mean I'm getting name.from same.json in array and other hand I'm getting values from some json but diffrent aaray and array name is similer to uppe