hi am new to flutter and i need to get data from a map using API I m struggling at the moment and don't know what to do I always keep getting a error Error '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable'
this is the class code
// To parse this JSON data, do
//
// final aziz = azizFromJson(jsonString);
import 'dart:convert';
Demandes azizFromJson(String str) => Demandes.fromJson(json.decode(str));
String azizToJson(Demandes data) => json.encode(data.toJson());
class Demandes {
Demandes({
required this.srMboSet,
});
SrMboSet srMboSet;
factory Demandes.fromJson(Map<String, dynamic> json) => Demandes(
srMboSet: SrMboSet.fromJson(json["SRMboSet"]),
);
Map<String, dynamic> toJson() => {
"SRMboSet": srMboSet.toJson(),
};
}
class SrMboSet {
SrMboSet({
required this.rsStart,
required this.rsCount,
required this.sr,
});
int rsStart;
int rsCount;
List<Sr> sr;
factory SrMboSet.fromJson(Map<String, dynamic> json) => SrMboSet(
rsStart: json["rsStart"],
rsCount: json["rsCount"],
sr: List<Sr>.from(json["SR"].map((x) => Sr.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"rsStart": rsStart,
"rsCount": rsCount,
"SR": List<dynamic>.from(sr.map((x) => x.toJson())),
};
}
class Sr {
Sr({
required this.rowstamp,
required this.attributes,
});
String rowstamp;
Attributes attributes;
factory Sr.fromJson(Map<String, dynamic> json) => Sr(
rowstamp: json["rowstamp"],
attributes: Attributes.fromJson(json["Attributes"]),
);
Map<String, dynamic> toJson() => {
"rowstamp": rowstamp,
"Attributes": attributes.toJson(),
};
}
class Attributes {
Attributes({
required this.ticketid,
required this.attributesClass,
required this.description,
required this.status,
required this.statusdate,
required this.reportedby,
});
Class ticketid;
Class attributesClass;
Class description;
Class status;
Class statusdate;
Class reportedby;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
ticketid: Class.fromJson(json["TICKETID"]),
attributesClass: Class.fromJson(json["CLASS"]),
description: Class.fromJson(json["DESCRIPTION"]),
status: Class.fromJson(json["STATUS"]),
statusdate: Class.fromJson(json["STATUSDATE"]),
reportedby: Class.fromJson(json["REPORTEDBY"]),
);
Map<String, dynamic> toJson() => {
"TICKETID": ticketid.toJson(),
"CLASS": attributesClass.toJson(),
"DESCRIPTION": description.toJson(),
"STATUS": status.toJson(),
"STATUSDATE": statusdate.toJson(),
"REPORTEDBY": reportedby.toJson(),
};
}
class Class {
Class({
required this.content,
});
String content;
factory Class.fromJson(Map<String, dynamic> json) => Class(
content: json["content"],
);
Map<String, dynamic> toJson() => {
"content": content,
};
}
and this is my main code I always get a error if anyone can help please
// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls
import 'dart:convert';
import './demandes.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DataFromAPI(),
);
}
}
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
class _DataFromAPIState extends State<DataFromAPI> {
List<Attributes> MyAllData = [];
#override
void initState() {
loadData();
}
loadData() async {
var response = await http.get(Uri.parse(
'http://192.168.1.30:9080/maxrest/rest/mbo/sr/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
String responseBody = response.body;
Map<String, dynamic> jsonBody = json.decode(responseBody);
for (var data in jsonBody) {
MyAllData.add(Attributes(
ticketid: data["ticketid"],
attributesClass: data["attributesClass"],
description: data["description"],
status: data["status"],
statusdate: data["statusdate"],
reportedby: data["reportedby"]));
}
setState(() {
MyAllData.forEach((somedata) => print("Name: ${somedata.ticketid}"));
});
} else {
print("theres something wrong...");
}
}
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: AppBar(
title: Text('Liste des SR'),
),
body: MyAllData.length == 0
? new Center(
child: new CircularProgressIndicator(),
)
: showMyUI(),
),
);
}
Widget showMyUI() {
return new ListView.builder(
itemCount: MyAllData.length,
itemBuilder: ((_, index) {
return new Container(
child: new Card(
child: new Container(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
'Ticket ID : ${MyAllData[index].ticketid}',
),
],
),
),
),
);
}));
}
}
So from your model class, what I see is that you have Attributes inside of Sr, but after your JSON decode, you went ahead to just add data to the attributes list, so that's where your error is coming from, you have not fully deserialised the data here's how you can do it and it would work
loadData() async {
var response = await http.get(Uri.parse(
'http://192.168.1.30:9080/maxrest/rest/mbo/sr/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.srMboSet.sr;
// SR is your list attributes is just an object, So what you do is this
for (int attribute = 0; attribute < srAttributes.length; attribute++) {
MyAllData.add(srAttributes[attribute].attributes);
}
setState(() {
MyAllData.forEach((somedata) => print("Name: ${somedata.ticketid}"));
});
} else {
print("theres something wrong...");
}
}
Related
I am trying to show a list of Json name that is obtained from an API but when I try to display it I receive type List error as result of snapshot.error. I am not sure exactly how and which line is resulting in this error.
Here is the screen dart:
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Future<List<Workouts_Model>> futureWorkouts;
#override
void initState() {
super.initState();
futureWorkouts = APIService.fetchUserWorkout();
}
....................................
FutureBuilder<List<Workouts_Model>>(
future: futureWorkouts,
builder: (BuildContext context,
AsyncSnapshot<List<Workouts_Model>> snapshot) {
if (snapshot.hasData) {
return Column(
children: List.generate(snapshot.data!.length,
(index) => Text(snapshot.data![index].name)));
} else if (snapshot.hasError) ;
print(snapshot.error);
// throw snapshot.error!;
// //
{
return Text('${snapshot.error}'); <———error here
}
return const CircularProgressIndicator();
},
),
Here is the api called:
static Future<List<Workouts_Model>> fetchUserWorkout() async {
final response = await http.get(Uri.parse(...),
headers: {...},);
final responseJson = jsonDecode(response.body);
if (response.statusCode == 200) {
return workoutsModelFromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User');
}
}
If I could get help on knowing why and how to solve it.
Here is the model:
List<Workouts_Model> workoutsModelFromJson(String str) =>
List<Workouts_Model>.from(
json.decode(str).map((x) => Workouts_Model.fromJson(x)));
String workoutsModelToJson(List<Workouts_Model> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Workouts_Model {
Workouts_Model({
required this.id,
required this.user,
required this.active,
required this.name,
required this.slug,
});
int id;
String user;
bool active;
String name;
String slug;
factory Workouts_Model.fromJson(Map<String, dynamic> json) => Workouts_Model(
id: json["id"],
user: json["user"],
active: json["active"],
name: json["name"],
slug: json["slug"],
);
Map<String, dynamic> toJson() => {
"id": id,
"user": user,
"active": active,
"name": name,
"slug": slug,
};
}
This is the result of final responseJson = jsonDecode(response.body); print(responseJson);
[{id: 4, user: Username, active: false, name: T-shirt1, slug: Upper1}, {id: 5, user: Username, active: false, name: T-shirt2, slug: Lower1}]
if you look closely you've already decoded your response.body which being past.
final responseJson = jsonDecode(response.body); // Decoded already
if (response.statusCode == 200) {
return workoutsModelFromJson(jsonDecode(response.body)); //// Decoded data is pasted to workoutsModelFromJson.
} else {
throw Exception('Failed to load User');
}
So your model "workoutsModelFromJson" should be
List<Workouts_Model> workoutsModelFromJson(dynamic decodedResponse) =>
List<Workouts_Model>.from(
decodedResponse.map((x) => Workouts_Model.fromJson(x)));
I've been having this problem when trying to connect API's in flutter. I'm not sure if this is a problem of not receiving the data or if there is an error in my code, any hekp would be greatly appreciated.
This is the code I have on the page
import 'package:ctrade/models/newsinfo.dart';
import 'package:ctrade/services/api_manager.dart';
import 'package:flutter/material.dart';
class PostsPage extends StatefulWidget {
const PostsPage({ Key? key }) : super(key: key);
#override
State<PostsPage> createState() => _PostsPageState();
}
class _PostsPageState extends State<PostsPage> {
late Future<Welcome> _Welcome; //error here
#override
void initState() {
_Welcome = API_Manager().getNews();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold (
appBar: AppBar(
title: Text('News App'),
),
body: Container(
child: FutureBuilder<Welcome>(
future: _Welcome,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
itemCount: 52,
itemBuilder:(context, index) {
var ticker = snapshot.data!.ticker[index];
return Container(
height: 100,
child: Row(
children: [
//Text(ticker)
],
),
);
});
}
else
return Center(child: CircularProgressIndicator());
},
),
)
);
}
}
This is the code on my API manager file (I defined the news_url in a different file)
import 'package:ctrade/constants/strings.dart';
import 'package:ctrade/models/newsinfo.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class API_Manager {
Future<Welcome> getNews() async{
var client = http.Client();
var Welcome;
try{
var response = await client.get(Uri.parse(Strings.news_url));
if(response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
Welcome = Welcome.fromJson(jsonMap);
}
}
catch(Exception)
{
return Welcome;
}
return Welcome;
}
}
This is the file with the parsed json
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Welcome {
Welcome({
required this.id,
required this.ticker,
required this.isin,
required this.bestAsk,
required this.bestBid,
required this.currentPrice,
required this.askVolume,
required this.bidVolume,
required this.fullCompanyName,
required this.prevPrice,
required this.prevPer,
required this.prevChange,
});
int id;
String ticker;
String isin;
String bestAsk;
String bestBid;
String currentPrice;
String askVolume;
String bidVolume;
String fullCompanyName;
String prevPrice;
String prevPer;
String prevChange;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
id: json["id"],
ticker: json["Ticker"],
isin: json["ISIN"],
bestAsk: json["Best_Ask"],
bestBid: json["Best_bid"],
currentPrice: json["Current_price"],
askVolume: json["Ask_Volume"],
bidVolume: json["Bid_Volume"],
fullCompanyName: json["FullCompanyName"],
prevPrice: json["PrevPrice"],
prevPer: json["PrevPer"],
prevChange: json["PrevChange"],
);
Map<String, dynamic> toJson() => {
"id": id,
"Ticker": ticker,
"ISIN": isin,
"Best_Ask": bestAsk,
"Best_bid": bestBid,
"Current_price": currentPrice,
"Ask_Volume": askVolume,
"Bid_Volume": bidVolume,
"FullCompanyName": fullCompanyName,
"PrevPrice": prevPrice,
"PrevPer": prevPer,
"PrevChange": prevChange,
};
}
class Welcome {
Welcome({
required this.id,
required this.ticker,
required this.isin,
required this.bestAsk,
required this.bestBid,
required this.currentPrice,
required this.askVolume,
required this.bidVolume,
required this.fullCompanyName,
required this.prevPrice,
required this.prevPer,
required this.prevChange,
});
int? id;
String? ticker;
String? isin;
String? bestAsk;
String? bestBid;
String? currentPrice;
String? askVolume;
String? bidVolume;
String? fullCompanyName;
String? prevPrice;
String? prevPer;
String? prevChange;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
id: json["id"]??"",
ticker: json["Ticker"]??"",
isin: json["ISIN"]??"",
bestAsk: json["Best_Ask"]??"",
bestBid: json["Best_bid"]??"",
currentPrice: json["Current_price"]??"",
askVolume: json["Ask_Volume"]??"",
bidVolume: json["Bid_Volume"]??"",
fullCompanyName: json["FullCompanyName"]??"",
prevPrice: json["PrevPrice"]??"",
prevPer: json["PrevPer"]??"",
prevChange: json["PrevChange"]??"",
);
Map<String, dynamic> toJson() => {
"id": id,
"Ticker": ticker,
"ISIN": isin,
"Best_Ask": bestAsk,
"Best_bid": bestBid,
"Current_price": currentPrice,
"Ask_Volume": askVolume,
"Bid_Volume": bidVolume,
"FullCompanyName": fullCompanyName,
"PrevPrice": prevPrice,
"PrevPer": prevPer,
"PrevChange": prevChange,
};
}
i fetch data from server using flutter http request and load more data when user scroll to bottom of screen. i receive this error "Unhandled Exception: type 'List' is not a subtype of type 'Product'". Please help, i struggle all day without success.
model.dart file
class Product {
final int id;
final String accountName,
callNumber,
whatsappNumber,
businessLocation,
caption;
final List<Images> productPhoto;
Product({
this.id,
this.accountName,
this.callNumber,
this.whatsappNumber,
this.businessLocation,
this.caption,
this.productPhoto,
});
// this is static method
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
accountName: json['account_name'],
callNumber: json['call_number'],
whatsappNumber:
json['whatsapp_number'] != null ? json['whatsapp_number'] : null,
businessLocation: json['business_location'],
caption: json['caption'],
productPhoto:
(json['post_photos'] as List).map((i) => Images.fromJson(i)).toList(),
);
}
}
class Images {
final String filename;
Images({this.filename});
factory Images.fromJson(Map<String, dynamic> json) {
return Images(
filename: json['filename'],
);
}
}
explore.dart file (i import models.dart to this file)
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:windowshoppi/models/global.dart';
import 'package:windowshoppi/models/product.dart';
import 'package:http/http.dart' as http;
class Explore extends StatefulWidget {
#override
_ExploreState createState() => _ExploreState();
}
class _ExploreState extends State<Explore> {
ScrollController _scrollController = ScrollController();
List<Product> data;
String nextUrl;
#override
void initState() {
// TODO: implement initState
super.initState();
this.fetchProduct(http.Client(), ALL_PRODUCT_URL);
_scrollController.addListener(() {
// print(_scrollController.position.pixels);
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if (nextUrl != null) {
this.fetchProduct(http.Client(), nextUrl);
}
// print(nextUrl);
}
});
}
Future<List<Product>> fetchProduct(http.Client client, url) async {
final response = await client.get(url);
if (response.statusCode == 200) {
Map<String, dynamic> mapResponse = json.decode(response.body);
nextUrl = mapResponse['next'];
if (mapResponse["count"] != "") {
final products = mapResponse["results"].cast<Map<String, dynamic>>();
final listOfProducts = await products.map<Product>((json) {
return Product.fromJson(json);
}).toList();
// return listOfProducts;
setState(() {
data.add(listOfProducts);
});
} else {
return [];
}
} else {
throw Exception('failed to load data from internet');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('http get'),
),
body: ListView.builder(
controller: _scrollController,
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Container(
height: 200,
color: Colors.blue,
child: Text(data[index].caption),
),
);
},
),
);
}
}
Have a look at this part of the code.
final listOfProducts = await products.map<Product>((json) {
return Product.fromJson(json);
}).toList();
In the .map() method you are casting it to type < Product >. So judging by the error you have mentioned, "Unhandled Exception: type 'List' is not a subtype of type Product"
I think the json data being returned contains a List, instead of the product fields. I would highly recommend you to once check the json data being returned, and double-check if you are targeting the correct JSON tree nodes.
Let me know if this solved the issue.
Hi everyone I got this exception (Unexpected character ) when I call this json.decode(jsonString), but some times when I run the app it doesn't throw any exception .
when this exception appear the expect data that comes from server doesn't displayed on the app .
I test my API in localhost .
my code :
Future<List<Governorate>> getGovernorates() async {
var governorates = List<Governorate>();
var governorate = await client.get('$endpoint/governorates');
String jsonString = governorate.body?.toString();
if(governorate.statusCode == 200){
//print("governorate =====> ${jsonString}");
var parsed= json.decode(jsonString) as List<dynamic>; // sometimes it's fails here and throw the exeption FormatException: Unexpected character
for(var gov in parsed){
governorates.add(Governorate.fromJson(gov));
}
} else {
throw "Can't get governorates";
}
return governorates;
}
json object :
[
{
"id": 1,
"governorate_name": "test governorate",
"governorate_cities": []
},
{
"id": 1,
"governorate_name": "test governorate 2",
"governorate_cities": [
{
"id": 11,
"city_name": "test city",
"governorate_id": 1
}
]
}
]
I try to solve this problem but I don't success I hope you guys give my the Idea about this problem and how can I solve it
Thanks for your attention. I’m looking forward to your answer.
Just check out the code that I have implemented based on your json provided.
This is the json you provided.
[
{
"id":1,
"governorate_name":"test governorate",
"governorate_cities":[
]
},
{
"id":1,
"governorate_name":"test governorate 2",
"governorate_cities":[
{
"id":11,
"city_name":"test city",
"governorate_id":1
}
]
}
]
And from the above json I have created a model class for it just check it out
// To parse this JSON data, do
//
// final governorate = governorateFromJson(jsonString);
import 'dart:convert';
List<Governorate> governorateFromJson(String str) => List<Governorate>.from(json.decode(str).map((x) => Governorate.fromJson(x)));
String governorateToJson(List<Governorate> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Governorate {
Governorate({
this.id,
this.governorateName,
this.governorateCities,
});
int id;
String governorateName;
List<GovernorateCity> governorateCities;
factory Governorate.fromJson(Map<String, dynamic> json) => Governorate(
id: json["id"],
governorateName: json["governorate_name"],
governorateCities: List<GovernorateCity>.from(json["governorate_cities"].map((x) => GovernorateCity.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"governorate_name": governorateName,
"governorate_cities": List<dynamic>.from(governorateCities.map((x) => x.toJson())),
};
}
class GovernorateCity {
GovernorateCity({
this.id,
this.cityName,
this.governorateId,
});
int id;
String cityName;
int governorateId;
factory GovernorateCity.fromJson(Map<String, dynamic> json) => GovernorateCity(
id: json["id"],
cityName: json["city_name"],
governorateId: json["governorate_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"city_name": cityName,
"governorate_id": governorateId,
};
}
And this is where I have shown a sample ui in the listview for the name.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isLoading = false;
List<Governorate> dataList = List();
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
#override
void initState() {
super.initState();
getData();
}
getData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadFromAssets();
final governorate = governorateFromJson(jsonString);
dataList = governorate;
setState(() {
_isLoading = false;
});
}
/*
// This will be in your case as per you code
Future<List<Governorate>> getGovernorates() async {
var governorates = List<Governorate>();
var governorate = await client.get('$endpoint/governorates');
String jsonString = governorate.body?.toString();
if(governorate.statusCode == 200){
return governorateFromJson(jsonString);
}
} */
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: Container(
child: ListView.builder(
itemCount: dataList.length,
shrinkWrap: true,
itemBuilder: (context, i) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(dataList[i].governorateName),
));
}),
),
);
}
}
This might happen because the list is empty just check the following code and let me know still the error occurs
Change the following factory method from the model class
factory NewMessagesModel.fromJson(Map<String, dynamic> json) => NewMessagesModel(
id: json["id"],
governorateName: json["governorate_name"],
governorateCities: json["governorate_cities"] ==null ?null:List<GovernorateCity>.from(json["governorate_cities"].map((x) => GovernorateCity.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"governorate_name": governorateName,
"governorate_cities":json["governorate_cities"] ==null?null : List<dynamic>.from(governorateCities.map((x) => x.toJson())),
};
}
just check the commented code where I have taken you api fetching code and made some modifications so that it would work and let me know if it works.
I'm trying to get data from API using Rest Service..
But I got an error saying that the getter was called on null, after doing some research, I found something, like the UI which the data I want to display was executed first than the getData function, it makes the system read the variable as null and the error occurs. Can anybody help me with this case..
Here this is a bit of my codes,
class PickUp extends StatefulWidget {
var created_name, wmsorders_id, id;
PickUp(
{Key key,
#required this.created_name,
#required this.wmsorders_id,
#required this.id})
: super(key: key);
#override
_PickUpState createState() => _PickUpState();
}
class _PickUpState extends State<PickUp> {
DetailModel detailModel;
String sender = "";
Future<String> getDetail() async {
print("id : " + widget.id);
var data = "id=" + widget.id + "";
var response_detail = await RestService()
.restRequestServiceGet(SystemParam.URL_DETAIL_UPCOMING, data);
print("response_detail : " + response_detail.body.toString());
setState(() {
detailModel = DetailModel.fromJson(jsonDecode(response_detail.body));
});
return "Success!";
}
#override
void initState() {
getDetail();
}
Widget build(BuildContext context) {
// NULL CHECKING
if (detailModel != null) {
print("sender =" +detailModel.the0.picName);
} else {
print("sender = null");
}
// I want to get picName from detail Model and using it in UI, but I got Error here
sender = detailModel.the0.picName';
print("sender = " +'$sender');
}
Here is the detailModel
// To parse this JSON data, do
//
// final detailModel = detailModelFromJson(jsonString);
import 'dart:convert';
DetailModel detailModelFromJson(String str) => DetailModel.fromJson(json.decode(str));
String detailModelToJson(DetailModel data) => json.encode(data.toJson());
class DetailModel {
The0 the0;
The0 the1;
Records records;
DetailModel({
this.the0,
this.the1,
this.records,
});
factory DetailModel.fromJson(Map<String, dynamic> json) => DetailModel(
the0: The0.fromJson(json["0"]),
the1: The0.fromJson(json["1"]),
records: Records.fromJson(json["records"]),
);
Map<String, dynamic> toJson() => {
"0": the0.toJson(),
"1": the1.toJson(),
"records": records.toJson(),
};
}
class Records {
int status;
String message;
Records({
this.status,
this.message,
});
factory Records.fromJson(Map<String, dynamic> json) => Records(
status: json["status"],
message: json["message"],
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
};
}
class The0 {
String id;
String sku;
int sak;
String qty;
String shipstatId;
String picName;
String picTelp;
String orderMultipleId;
String orderdetId;
String coordinatorId;
The0({
this.id,
this.sku,
this.sak,
this.qty,
this.shipstatId,
this.picName,
this.picTelp,
this.orderMultipleId,
this.orderdetId,
this.coordinatorId,
});
factory The0.fromJson(Map<String, dynamic> json) => The0(
id: json["id"],
sku: json["sku"],
sak: json["sak"],
qty: json["qty"],
shipstatId: json["shipstat_id"],
picName: json["pic_name"],
picTelp: json["pic_telp"],
orderMultipleId: json["order_multiple_id"],
orderdetId: json["orderdet_id"],
coordinatorId: json["coordinator_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"sku": sku,
"sak": sak,
"qty": qty,
"shipstat_id": shipstatId,
"pic_name": picName,
"pic_telp": picTelp,
"order_multiple_id": orderMultipleId,
"orderdet_id": orderdetId,
"coordinator_id": coordinatorId,
};
}
And here is the Error,
You need to use FutureBuilder in build method and wait until response.
Remove setstate and Modify the code as below.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Test',
style: TextStyle(
color: Colors.white,
),
),
),
body: FutureBuilder<DetailModel>(
future: getDetail(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print("Here you can get data "+snapshot.data.toString());
} else {
print("Waiting mode");
return Container(
color: Colors.blue,
);
}
},
),
);
}
}