Flutter is not returning an api call - json

So I am trying to parse some json with http my method of parsing in this
Future<bool> fetchUser(username) async {
setLoading(true);
await Osu(username).fetchUser().then((data) {
setLoading(false);
if (data.statusCode == 200) {
setUser(UserInfo.fromJson(json.decode(data.body)));
} else {
print(data.body);
Map<String, dynamic> result = json.decode(data.body);
setMessage(result['message']);
}
});
return isUser();
}
class UserInfo {
String userId;
String username;
DateTime joinDate;
String count300;
String count100;
String count50;
String playcount;
String rankedScore;
String totalScore;
String ppRank;
String level;
String ppRaw;
String accuracy;
String countRankSs;
String countRankSsh;
String countRankS;
String countRankSh;
String countRankA;
String country;
String totalSecondsPlayed;
String ppCountryRank;
List<dynamic> events;
UserInfo({
this.userId,
this.username,
this.joinDate,
this.count300,
this.count100,
this.count50,
this.playcount,
this.rankedScore,
this.totalScore,
this.ppRank,
this.level,
this.ppRaw,
this.accuracy,
this.countRankSs,
this.countRankSsh,
this.countRankS,
this.countRankSh,
this.countRankA,
this.country,
this.totalSecondsPlayed,
this.ppCountryRank,
this.events,
});
Map toJson() => {
"user_id": userId == null ? null : userId,
"username": username == null ? null : username,
"join_date": joinDate == null ? null : joinDate.toIso8601String(),
"count300": count300 == null ? null : count300,
"count100": count100 == null ? null : count100,
"count50": count50 == null ? null : count50,
"playcount": playcount == null ? null : playcount,
"ranked_score": rankedScore == null ? null : rankedScore,
"total_score": totalScore == null ? null : totalScore,
"pp_rank": ppRank == null ? null : ppRank,
"level": level == null ? null : level,
"pp_raw": ppRaw == null ? null : ppRaw,
"accuracy": accuracy == null ? null : accuracy,
"count_rank_ss": countRankSs == null ? null : countRankSs,
"count_rank_ssh": countRankSsh == null ? null : countRankSsh,
"count_rank_s": countRankS == null ? null : countRankS,
"count_rank_sh": countRankSh == null ? null : countRankSh,
"count_rank_a": countRankA == null ? null : countRankA,
"country": country == null ? null : country,
"total_seconds_played":
totalSecondsPlayed == null ? null : totalSecondsPlayed,
"pp_country_rank": ppCountryRank == null ? null : ppCountryRank,
"events":
events == null ? null : List<dynamic>.from(events.map((x) => x)),
};
UserInfo.fromJson(Map json)
: userId = json["user_id"] == null ? null : json["user_id"],
username = json["username"] == null ? null : json["username"],
joinDate = json["join_date"] == null
? null
: DateTime.parse(json["join_date"]),
count300 = json["count300"] == null ? null : json["count300"],
count100 = json["count100"] == null ? null : json["count100"],
count50 = json["count50"] == null ? null : json["count50"],
playcount = json["playcount"] == null ? null : json["playcount"],
rankedScore =
json["ranked_score"] == null ? null : json["ranked_score"],
totalScore = json["total_score"] == null ? null : json["total_score"],
ppRank = json["pp_rank"] == null ? null : json["pp_rank"],
level = json["level"] == null ? null : json["level"],
ppRaw = json["pp_raw"] == null ? null : json["pp_raw"],
accuracy = json["accuracy"] == null ? null : json["accuracy"],
countRankSs =
json["count_rank_ss"] == null ? null : json["count_rank_ss"],
countRankSsh =
json["count_rank_ssh"] == null ? null : json["count_rank_ssh"],
countRankS = json["count_rank_s"] == null ? null : json["count_rank_s"],
countRankSh =
json["count_rank_sh"] == null ? null : json["count_rank_sh"],
countRankA = json["count_rank_a"] == null ? null : json["count_rank_a"],
country = json["country"] == null ? null : json["country"],
totalSecondsPlayed = json["total_seconds_played"] == null
? null
: json["total_seconds_played"],
ppCountryRank =
json["pp_country_rank"] == null ? null : json["pp_country_rank"],
events = json["events"] == null
? null
: List<dynamic>.from(json["events"].map((x) => x));
}
And then this is my request call:
import 'package:http/http.dart' as http;
class Osu {
final String userName;
final String url = 'https://osu.ppy.sh/api';
static String apiKey = 'wewewewewwweojjfoejfe';
Osu(this.userName);
Future<http.Response> fetchUser() {
return http.get(url + '/get_user' + "?u=$userName" + "&k=$apiKey");
}
}
I have tried returning it in a list but i just get the same error and advice?
The error I get is:
TypeError (type 'List' is not a subtype of type 'Map')
on line
await Osu(username).fetchUser().then((data) {
Thank you!
I am not sure if it is not mapping correctly or that I am messing up the call itself. Either way I have been extremely stumped on this for the past 30m and can't seem to solve it.
Updated with json:
[
{
"user_id": "9795284",
"username": "SakuraMotion",
"join_date": "2017-02-24 17:41:13",
"count300": "4155343",
"count100": "655286",
"count50": "64939",
"playcount": "25758",
"ranked_score": "8433289241",
"total_score": "20762480956",
"pp_rank": "84925",
"level": "99.3314",
"pp_raw": "3318.78",
"accuracy": "95.20140075683594",
"count_rank_ss": "5",
"count_rank_ssh": "0",
"count_rank_s": "473",
"count_rank_sh": "1",
"count_rank_a": "942",
"country": "US",
"total_seconds_played": "1467366",
"pp_country_rank": "14317",
"events": []
}
updated with data.body response:
[
{
"user_id": "9795284",
"username": "SakuraMotion",
"join_date": "2017-02-24 17:41:13",
"count300": "4185533",
"count100": "658232",
"count50": "65063",
"playcount": "26008",
"ranked_score": "8509686083",
"total_score": "20977676803",
"pp_rank": "84295",
"level": "99.3547",
"pp_raw": "3333.68",
"accuracy": "95.1374740600586",
"count_rank_ss": "5",
"count_rank_ssh": "0",
"count_rank_s": "477",
"count_rank_sh": "1",
"count_rank_a": "950",
"country": "US",
"total_seconds_played": "1475942",
"pp_country_rank": "14224",
"events": [
{
"display_html": "<img src='/images/C_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #842 on <a href='/b/1771455?m=3'>Cranky vs. MASAKI - ouroboros -twin stroke of the end- [4K CS' Normal]</a> (osu!mania)",
"beatmap_id": "1771455",
"beatmapset_id": "845135",
"date": "2019-10-19 01:24:15",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #812 on <a href='/b/2115037?m=0'>Kousaka Honoka (CV: Nitta Emi) - Snow halation (HONOKA Mix) [Devotion]</a> (osu!)",
"beatmap_id": "2115037",
"beatmapset_id": "982344",
"date": "2019-10-19 01:08:44",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #377 on <a href='/b/2173646?m=0'>Roselia - Charles [Expert]</a> (osu!)",
"beatmap_id": "2173646",
"beatmapset_id": "1032239",
"date": "2019-10-19 01:05:46",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #70 on <a href='/b/2123647?m=0'>Reol - Jitter Doll [Extra]</a> (osu!)",
"beatmap_id": "2123647",
"beatmapset_id": "1010993",
"date": "2019-10-19 01:02:50",
"epicfactor": "1"
}
]
}
]

Pay attention to the error as it is clearly stating your issue: type 'List<dynamic>' is not a subtype of type 'Map, not sure if it is actually on fetch but
Find documentation for https://osu.ppy.sh/api/get_user API and confirm response. You can also test command line by doing:
curl -X GET https://osu.ppy.sh/api/get_user&u=USERNAME&k=KEY
and ensure you are getting 200 and correct structure.

I think the error is on this line
Map<String, dynamic> result = json.decode(data.body);
The result of the json.decode(data.body) is actually a List but you assigned it to Map
I think you can change it to
List<Dynamic> result = json.decode(data.body);
or
List result = json.decode(data.body);
If you really need to Map it, you can Map it later from the List

There is a multitude of reasons that you might be getting the error... it would be beneficial to provide a sample of the JSON that the API is returning.
You can check your UserInfo()... it has the following field:
List<dynamic> events;
Double check if the events coming from the JSON is really a List.
If you are having an issue with parsing complex JSON files... better use JsonSerializable https://flutter.dev/docs/development/data-and-backend/json#creating-model-classes-the-json_serializable-way

Related

How to catch nulls and give defaults to an entire array(Transform function in Dataweave)?

I used an elseif function to prevent my API from failing due to null values.
"4435555555"
else if ( payload.ship_address.phone as String != "")
payload.ship_address.phone
else
"4435555555"
var cust_name = if ( payload.ship_address.name == null)
"Client Customer"
else if (payload.ship_address.name as String == "")
"Client Customer"
else
payload.ship_address.name
I know I could do this for every value by doing a ton of functions but is there a way to do this for the entire array in one function?
var telephoneNumber = if ( payload.ship_address.phone == null)
"4435555555"
else if ( payload.ship_address.phone as String != "")
payload.ship_address.phone
else
"4435555555"
var cust_name = if ( payload.ship_address.name == null)
"Client Customer"
else if (payload.ship_address.name as String == "")
"Client Customer"
else
payload.ship_address.name
---
{
order: {
client_identifier: payload.po,
brand: "CLIENT_BRAND",
shipping_method: shippingMethod default "Standard",
price_cents: floor (payload.total as Number * 100),
channel: "rts_dropship",
tax_cents: 0,
shipping_cost_cents: 0,
shipping_tax_cents: 0,
billing_address: {
name: cust_name default "Client Customer",
telephone_number: telephoneNumber,
street: payload.ship_address.line1,
city: payload.ship_address.city,
state: payload.ship_address.state,
zip_code: payload.ship_address.postal_code,
country: payload.ship_address.country,
street2: payload.ship_address.line2,
company: payload.ship_address.company
},
shipping_address: {
name: cust_name default "Client Customer",
telephone_number: telephoneNumber,
street: payload.ship_address.line1,
city: payload.ship_address.city,
state: payload.ship_address.state,
zip_code: payload.ship_address.postal_code,
country: payload.ship_address.country,
street2: payload.ship_address.line2,
company: payload.ship_address.company
},
order_items: payload.items map ( item , indexOfItem ) -> {
client_identifier: item.id,
sku: item.quants.vpc[0],
condition: "N",
quantity: item.quants.quantity[0] as Number,
price_cents: floor ((item.unit_cost as Number default 0) * 100),
tax_cents: 0,
shipping_cost_cents: 0,
shipping_tax_cents: 0,
brand: item.brand_name,
comments: payload.vendor_notes default ""
},
packing_slip_identifier: payload.items.quants[0].ositems[0].order_channel_refnum[0]
}
}
You can create a Helper function using the isEmpty function and use it like you use default keyword.
%dw 2.0
output application/json
fun ifEmptyThen(string, defaultValue) =
if(isEmpty(string)) defaultValue
else string
---
{
nonEmptyValue: "nonEmpty" ifEmptyThen "defaultForNonEmpty",
blankString: "" ifEmptyThen "defaultForBlankString",
nullValue: null ifEmptyThen "defaultForNull"
}
The output of this will look like:
{
"nonEmptyValue": "nonEmpty",
"blankString": "defaultForBlankString",
"nullValue": "defaultForNull"
}

How to get List from api in flutter

I'm Trying to get a list of users from my api through ApiService and model it in my UserModel class.
It's giving me this error The argument type 'List<Result>?' can't be assigned to the parameter type 'List<Result>'.
The results are also not showing on the screen.
Much obliged
If the provided code is not enough and you want to take a look at the full project, here's the repo:
https://github.com/renslakens/SkoolWorkshopApp.git
UserModel class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
class UserModel {
UserModel({
required this.status,
required this.result,
});
int status;
List<Result> result;
factory UserModel.fromJson(Map<String, dynamic> json) =>
UserModel(
status: json["status"] == null ? null : json["status"],
result: json["result"] == null ? null : List<Result>.from(
json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() =>
{
"status": status == null ? null : status,
"result": result == null ? null : List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result userModelFromJson(String str) => Result.fromJson(json.decode(str));
String userModelToJson(UserModel data) => json.encode(data.toJson());
Result({
required this.docentId,
required this.naam,
required this.achternaam,
required this.emailadres,
required this.geboortedatum,
required this.geboorteplaats,
this.maxRijafstand,
this.heeftRijbewijs,
this.heeftAuto,
required this.straat,
required this.huisnummer,
required this.geslacht,
required this.nationaliteit,
required this.woonplaats,
required this.postcode,
required this.land,
required this.wachtwoord,
required this.isAccepted,
this.isFlexwerker,
});
int docentId;
String naam;
String achternaam;
String emailadres;
String geboortedatum;
String geboorteplaats;
dynamic maxRijafstand;
dynamic heeftRijbewijs;
dynamic heeftAuto;
String straat;
int huisnummer;
String geslacht;
String nationaliteit;
String woonplaats;
String postcode;
String land;
String wachtwoord;
int isAccepted;
dynamic isFlexwerker;
factory Result.fromJson(Map<String, dynamic> json) =>
Result(
docentId: json["docentID"] == null ? null : json["docentID"],
naam: json["naam"] == null ? null : json["naam"],
achternaam: json["achternaam"] == null ? null : json["achternaam"],
emailadres: json["emailadres"] == null ? null : json["emailadres"],
geboortedatum: json["geboortedatum"] == null ? null : (json["geboortedatum"]),
geboorteplaats: json["geboorteplaats"] == null
? null
: json["geboorteplaats"],
maxRijafstand: json["maxRijafstand"],
heeftRijbewijs: json["heeftRijbewijs"],
heeftAuto: json["heeftAuto"],
straat: json["straat"] == null ? null : json["straat"],
huisnummer: json["huisnummer"] == null ? null : json["huisnummer"],
geslacht: json["geslacht"] == null ? null : json["geslacht"],
nationaliteit: json["nationaliteit"] == null
? null
: json["nationaliteit"],
woonplaats: json["woonplaats"] == null ? null : json["woonplaats"],
postcode: json["postcode"] == null ? null : json["postcode"],
land: json["land"] == null ? null : json["land"],
wachtwoord: json["wachtwoord"] == null ? null : json["wachtwoord"],
isAccepted: json["isAccepted"] == null ? null : json["isAccepted"],
isFlexwerker: json["isFlexwerker"],
);
Map<String, dynamic> toJson() =>
{
"docentID": docentId == null ? null : docentId,
"naam": naam == null ? null : naam,
"achternaam": achternaam == null ? null : achternaam,
"emailadres": emailadres == null ? null : emailadres,
"geboortedatum": geboortedatum == null ? null : geboortedatum,
"geboorteplaats": geboorteplaats == null ? null : geboorteplaats,
"maxRijafstand": maxRijafstand,
"heeftRijbewijs": heeftRijbewijs,
"heeftAuto": heeftAuto,
"straat": straat == null ? null : straat,
"huisnummer": huisnummer == null ? null : huisnummer,
"geslacht": geslacht == null ? null : geslacht,
"nationaliteit": nationaliteit == null ? null : nationaliteit,
"woonplaats": woonplaats == null ? null : woonplaats,
"postcode": postcode == null ? null : postcode,
"land": land == null ? null : land,
"wachtwoord": wachtwoord == null ? null : wachtwoord,
"isAccepted": isAccepted == null ? null : isAccepted,
"isFlexwerker": isFlexwerker,
};
}
APIService class
class ApiService {
Future<List<UserModel>> getUsers() async {
try {
var url = Uri.parse(apis.baseUrl + apis.getUsers);
var response = await http.get(url);
if (response.statusCode == 200) {
List<UserModel> model = userModelFromJson(response.body);
return model;
}
} catch (e) {
log(e.toString());
}
}
}
Results from the API to list all the imported users
{
"status": 200,
"result": [
{
"docentID": 1,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "meel#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$kcVpe9yOdKzMPdEUcMIATOh3PE42GDiQfDLZeufKxpLpTb51Af7Ay",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 4,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "123mail123#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$jNx8CrBRw78VZdoTTomGWuVF4CEa6wcMMsIzmkHak1WjRVsfHaX86",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 7,
"naam": "Peter",
"achternaam": "gerritsen",
"emailadres": "test1#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$JRbNe40U7Fk2hcA4B4bgEe9ElmCX5dCovf5FNtZTLHLCX8v/DeiN2",
"isAccepted": 0,
"isFlexwerker": null
}
]
}

SignalR json api problem in Flutter (FormatException: Unexpected character (at character 4)

I am new to flutter and I try use signalr at my project. Actually I succeed login, simple parameter and token. But I need multi parameter for my app. My friend prepared API for me. We must use one more parameter. I try same coding but I take a below error.
I wonder where I make mistakes? I tried different models but everytime I take same error.
My json model is
[[
{"aciklama": "Description 1",
"ad": "Ad 1",
"adres": "Adres 1",
"bolge": "Bölge 1",
"cepNo": "0123456789",
"ePosta": "asd#asd.com",
"faksNo": "01234567890",
"ilce": "İlçe 1",
"sehir": "Şehir 1",
"telefonNo": "01234567890",
"vergiDairesi": "Vergi Dairesi 1",
"vergiNo": "987654321",
"yetkili": "Yetkili 1"},
{"aciklama": "Description 2",
"ad": "Ad 2",
"adres": "Adres 2",
"bolge": "Bölge 2",
"cepNo": "0123456789",
"ePosta": "asd#asd.com",
"faksNo": "01234567890",
"ilce": "İlçe 2",
"sehir": "Şehir 2",
"telefonNo": "01234567890",
"vergiDairesi": "Vergi Dairesi 2",
"vergiNo": "987654321",
"yetkili": "Yetkili 2"},
]]
And then I use https://app.quicktype.io/. I convert to dart model. You can see below
// To parse this JSON data, do
//
// final musteri = musteriFromJson(jsonString);
import 'dart:convert';
List<Musteri> musteriFromJson(String str) =>
List<Musteri>.from(json.decode(str).map((x) => Musteri.fromJson(x)));
String musteriToJson(List<Musteri> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Musteri {
Musteri({
this.aciklama,
this.ad,
this.adres,
this.bolge,
this.cepNo,
this.ePosta,
this.faksNo,
this.ilce,
this.sehir,
this.telefonNo,
this.vergiDairesi,
this.vergiNo,
this.yetkili,
});
String aciklama;
String ad;
String adres;
String bolge;
String cepNo;
String ePosta;
String faksNo;
String ilce;
String sehir;
String telefonNo;
String vergiDairesi;
String vergiNo;
String yetkili;
factory Musteri.fromJson(Map<String, dynamic> json) => Musteri(
aciklama: json["aciklama"] == null ? null : json["aciklama"],
ad: json["ad"] == null ? null : json["ad"],
adres: json["adres"] == null ? null : json["adres"],
bolge: json["bolge"] == null ? null : json["bolge"],
cepNo: json["cepNo"] == null ? null : json["cepNo"],
ePosta: json["ePosta"] == null ? null : json["ePosta"],
faksNo: json["faksNo"] == null ? null : json["faksNo"],
ilce: json["ilce"] == null ? null : json["ilce"],
sehir: json["sehir"] == null ? null : json["sehir"],
telefonNo: json["telefonNo"] == null ? null : json["telefonNo"],
vergiDairesi:
json["vergiDairesi"] == null ? null : json["vergiDairesi"],
vergiNo: json["vergiNo"] == null ? null : json["vergiNo"],
yetkili: json["yetkili"] == null ? null : json["yetkili"],
);
Map<String, dynamic> toJson() => {
"aciklama": aciklama == null ? null : aciklama,
"ad": ad == null ? null : ad,
"adres": adres == null ? null : adres,
"bolge": bolge == null ? null : bolge,
"cepNo": cepNo == null ? null : cepNo,
"ePosta": ePosta == null ? null : ePosta,
"faksNo": faksNo == null ? null : faksNo,
"ilce": ilce == null ? null : ilce,
"sehir": sehir == null ? null : sehir,
"telefonNo": telefonNo == null ? null : telefonNo,
"vergiDairesi": vergiDairesi == null ? null : vergiDairesi,
"vergiNo": vergiNo == null ? null : vergiNo,
"yetkili": yetkili == null ? null : yetkili,
};
}
And I wrote the codes as below in my view file.
_signalRSantralService.connection.on("Musteriler", (data) {
if (data != null) {
var musteriler = musteriFromJson(data.toString());
debugPrint("işlem tamamlandı");
// musterilerStream.sink.add(musteriler);
}
});
I clicked button and I received this message in terminal. This error : "FormatException: Unexpected character (at character 4)"
I/flutter ( 9934): LogLevel.trace: (WebSockets transport) data received. String data of length '567'
I/flutter ( 9934): LogLevel.error: A callback for the method musteriler threw error 'FormatException: Unexpected character (at character 4)
I/flutter ( 9934): [[{aciklama: Açıklama, ad: Ad, adres: Adres, bolge: Bölge, cepNo: 012345678...
I/flutter ( 9934): ^
I/flutter ( 9934): '.
I/flutter ( 9934): LogLevel.trace: (WebSockets transport) data received. String data of length '11'
How can I edit this error ?
You JSON data contains Nested lists. You'll need to do:
json.decode(data[0]) instead of json.decode(data).
I did it. I used the below code and I received data. This code is come from my model.
List<Musteri> musteriler =
List<Musteri>.from(data[0].map((model) => Musteri.fromJson(model)));

Flutter http.get not getting body data

I am trying to get the data from my json feed which is this Json
But when I try to use the body result it is not working ( but it works with other jsons like this one https://jsonplaceholder.typicode.com/users), my code looks like this:
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'noticias.dart';
class Services {
static const String url =
'https://studiofutbol.com.ec/api/json/feed_master.php?pagina=';
static Future<Portada> getNoticias() async {
try {
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
};
final response = await http.get(url, headers: headers);
debugPrint(response.body);
if (200 == response.statusCode) {
final Portada noticiasportada = portadaFromJson(response.body);
return noticiasportada;
} else {
return Portada();
}
} catch (e) {
return Portada();
}
}
}
I added those headers but it did not help, what could be causing the issue?
It work for me like this
Future<Portada> getNoticias() async {
try {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.getUrl(Uri.parse(
"https://studiofutbol.com.ec/api/json/feed_master.php?pagina="));
request.headers.set('content-type', 'application/json');
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
httpClient.close();
Map<String, dynamic> map = json.decode(reply);
final Portada noticiasportada = Portada.fromMap(map);
return noticiasportada;
} catch (e) {
return Portada();
}
}
Model Class
import 'dart:convert';
Portada portadaFromMap(String str) => Portada.fromMap(json.decode(str));
String portadaToMap(Portada data) => json.encode(data.toMap());
class Portada {
Portada({
this.json,
this.menu,
this.banners,
this.tags,
this.equipos,
this.menuIos,
this.version,
this.versionIos,
});
List<Json> json;
List<Menu> menu;
Banners banners;
List<Tag> tags;
List<Equipo> equipos;
List<MenuIo> menuIos;
String version;
String versionIos;
factory Portada.fromMap(Map<String, dynamic> json) => Portada(
json: json["Json"] == null ? null : List<Json>.from(json["Json"].map((x) => Json.fromMap(x))),
menu: json["menu"] == null ? null : List<Menu>.from(json["menu"].map((x) => Menu.fromMap(x))),
banners: json["banners"] == null ? null : Banners.fromMap(json["banners"]),
tags: json["tags"] == null ? null : List<Tag>.from(json["tags"].map((x) => Tag.fromMap(x))),
equipos: json["equipos"] == null ? null : List<Equipo>.from(json["equipos"].map((x) => Equipo.fromMap(x))),
menuIos: json["menu_ios"] == null ? null : List<MenuIo>.from(json["menu_ios"].map((x) => MenuIo.fromMap(x))),
version: json["version"] == null ? null : json["version"],
versionIos: json["version_ios"] == null ? null : json["version_ios"],
);
Map<String, dynamic> toMap() => {
"Json": json == null ? null : List<dynamic>.from(json.map((x) => x.toMap())),
"menu": menu == null ? null : List<dynamic>.from(menu.map((x) => x.toMap())),
"banners": banners == null ? null : banners.toMap(),
"tags": tags == null ? null : List<dynamic>.from(tags.map((x) => x.toMap())),
"equipos": equipos == null ? null : List<dynamic>.from(equipos.map((x) => x.toMap())),
"menu_ios": menuIos == null ? null : List<dynamic>.from(menuIos.map((x) => x.toMap())),
"version": version == null ? null : version,
"version_ios": versionIos == null ? null : versionIos,
};
}
class Banners {
Banners({
this.splash,
this.splashiphone,
this.main,
this.interna,
});
Interna splash;
Interna splashiphone;
Interna main;
Interna interna;
factory Banners.fromMap(Map<String, dynamic> json) => Banners(
splash: json["splash"] == null ? null : Interna.fromMap(json["splash"]),
splashiphone: json["splashiphone"] == null ? null : Interna.fromMap(json["splashiphone"]),
main: json["main"] == null ? null : Interna.fromMap(json["main"]),
interna: json["interna"] == null ? null : Interna.fromMap(json["interna"]),
);
Map<String, dynamic> toMap() => {
"splash": splash == null ? null : splash.toMap(),
"splashiphone": splashiphone == null ? null : splashiphone.toMap(),
"main": main == null ? null : main.toMap(),
"interna": interna == null ? null : interna.toMap(),
};
}
class Interna {
Interna({
this.imagen,
this.link,
});
String imagen;
String link;
factory Interna.fromMap(Map<String, dynamic> json) => Interna(
imagen: json["imagen"] == null ? null : json["imagen"],
link: json["link"] == null ? null : json["link"],
);
Map<String, dynamic> toMap() => {
"imagen": imagen == null ? null : imagen,
"link": link == null ? null : link,
};
}
class Equipo {
Equipo({
this.id,
this.nombre,
});
int id;
String nombre;
factory Equipo.fromMap(Map<String, dynamic> json) => Equipo(
id: json["id"] == null ? null : json["id"],
nombre: json["nombre"] == null ? null : json["nombre"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"nombre": nombre == null ? null : nombre,
};
}
class Json {
Json({
this.id,
this.title,
this.titleint,
this.permalink,
this.content,
this.excerpt,
this.date,
this.author,
this.image,
this.fuente,
this.thumbnail,
this.categories,
this.tags,
this.contentIphone,
this.videoEnlace,
});
int id;
String title;
String titleint;
String permalink;
String content;
String excerpt;
DateTime date;
String author;
List<dynamic> image;
String fuente;
String thumbnail;
List<String> categories;
List<String> tags;
String contentIphone;
String videoEnlace;
factory Json.fromMap(Map<String, dynamic> json) => Json(
id: json["id"] == null ? null : json["id"],
title: json["title"] == null ? null : json["title"],
titleint: json["titleint"] == null ? null : json["titleint"],
permalink: json["permalink"] == null ? null : json["permalink"],
content: json["content"] == null ? null : json["content"],
excerpt: json["excerpt"] == null ? null : json["excerpt"],
date: json["date"] == null ? null : DateTime.parse(json["date"]),
author: json["author"] == null ? null : json["author"],
image: json["image"] == null ? null : List<dynamic>.from(json["image"].map((x) => x)),
fuente: json["fuente"] == null ? null : json["fuente"],
thumbnail: json["thumbnail"] == null ? null : json["thumbnail"],
categories: json["categories"] == null ? null : List<String>.from(json["categories"].map((x) => x)),
tags: json["tags"] == null ? null : List<String>.from(json["tags"].map((x) => x)),
contentIphone: json["contentIphone"] == null ? null : json["contentIphone"],
videoEnlace: json["video_enlace"] == null ? null : json["video_enlace"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"titleint": titleint == null ? null : titleint,
"permalink": permalink == null ? null : permalink,
"content": content == null ? null : content,
"excerpt": excerpt == null ? null : excerpt,
"date": date == null ? null : date.toIso8601String(),
"author": author == null ? null : author,
"image": image == null ? null : List<dynamic>.from(image.map((x) => x)),
"fuente": fuente == null ? null : fuente,
"thumbnail": thumbnail == null ? null : thumbnail,
"categories": categories == null ? null : List<dynamic>.from(categories.map((x) => x)),
"tags": tags == null ? null : List<dynamic>.from(tags.map((x) => x)),
"contentIphone": contentIphone == null ? null : contentIphone,
"video_enlace": videoEnlace == null ? null : videoEnlace,
};
}
class Menu {
Menu({
this.url,
this.nombre,
});
String url;
String nombre;
factory Menu.fromMap(Map<String, dynamic> json) => Menu(
url: json["url"] == null ? null : json["url"],
nombre: json["nombre"] == null ? null : json["nombre"],
);
Map<String, dynamic> toMap() => {
"url": url == null ? null : url,
"nombre": nombre == null ? null : nombre,
};
}
class MenuIo {
MenuIo({
this.nombre,
this.url,
this.segue,
this.img,
});
String nombre;
String url;
String segue;
String img;
factory MenuIo.fromMap(Map<String, dynamic> json) => MenuIo(
nombre: json["nombre"] == null ? null : json["nombre"],
url: json["url"] == null ? null : json["url"],
segue: json["segue"] == null ? null : json["segue"],
img: json["img"] == null ? null : json["img"],
);
Map<String, dynamic> toMap() => {
"nombre": nombre == null ? null : nombre,
"url": url == null ? null : url,
"segue": segue == null ? null : segue,
"img": img == null ? null : img,
};
}
class Tag {
Tag({
this.id,
this.nombre,
this.url,
});
int id;
String nombre;
String url;
factory Tag.fromMap(Map<String, dynamic> json) => Tag(
id: json["id"] == null ? null : json["id"],
nombre: json["nombre"] == null ? null : json["nombre"],
url: json["url"] == null ? null : json["url"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"nombre": nombre == null ? null : nombre,
"url": url == null ? null : url,
};
}

FromJson return null , flutter

I have this model
class Meal {
Meal({
this.strMeal,
this.strMealThumb,
this.idMeal,
});
String strMeal;
String strMealThumb;
String idMeal;
factory Meal.fromJson(Map<String, dynamic> json) => Meal(
strMeal: json["strMeal"],
strMealThumb: json["strMealThumb"],
idMeal: json["idMeal"],
);
}
with help of the HTTP package on flutter, I'm making this request:
class RemoteServices {
static var client = http.Client();
static Future<Meal> fetchMealById(String id) async {
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Meal meal = Meal.fromJson(json.decode(response.body));
print(meal.idMeal);
} else {
throw Exception("Unable to Load");
}
}
}
I'm getting a Null value after decoding the response, although the response body before decoding is not null and contain an object that holds my data
You can copy paste run full code below
Data returned from your url is List<Meal> not Meal
You can reference model detail in full code
code snippet
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
class Payload {
Payload({
this.meals,
});
List<Meal> meals;
...
static Future<List<Meal>> fetchMealById(String id) async {
print(id);
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Payload payload = payloadFromJson(response.body);
return payload.meals;
...
FutureBuilder(
future: _future("yourId"),
builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
print(snapshot.data.runtimeType);
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[index].idMeal.toString()),
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
Payload({
this.meals,
});
List<Meal> meals;
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
meals: json["meals"] == null
? null
: List<Meal>.from(json["meals"].map((x) => Meal.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"meals": meals == null
? null
: List<dynamic>.from(meals.map((x) => x.toJson())),
};
}
class Meal {
Meal({
this.idMeal,
this.strMeal,
this.strDrinkAlternate,
this.strCategory,
this.strArea,
this.strInstructions,
this.strMealThumb,
this.strTags,
this.strYoutube,
this.strIngredient1,
this.strIngredient2,
this.strIngredient3,
this.strIngredient4,
this.strIngredient5,
this.strIngredient6,
this.strIngredient7,
this.strIngredient8,
this.strIngredient9,
this.strIngredient10,
this.strIngredient11,
this.strIngredient12,
this.strIngredient13,
this.strIngredient14,
this.strIngredient15,
this.strIngredient16,
this.strIngredient17,
this.strIngredient18,
this.strIngredient19,
this.strIngredient20,
this.strMeasure1,
this.strMeasure2,
this.strMeasure3,
this.strMeasure4,
this.strMeasure5,
this.strMeasure6,
this.strMeasure7,
this.strMeasure8,
this.strMeasure9,
this.strMeasure10,
this.strMeasure11,
this.strMeasure12,
this.strMeasure13,
this.strMeasure14,
this.strMeasure15,
this.strMeasure16,
this.strMeasure17,
this.strMeasure18,
this.strMeasure19,
this.strMeasure20,
this.strSource,
this.dateModified,
});
String idMeal;
String strMeal;
dynamic strDrinkAlternate;
String strCategory;
String strArea;
String strInstructions;
String strMealThumb;
String strTags;
String strYoutube;
String strIngredient1;
String strIngredient2;
String strIngredient3;
String strIngredient4;
String strIngredient5;
String strIngredient6;
String strIngredient7;
String strIngredient8;
String strIngredient9;
String strIngredient10;
String strIngredient11;
String strIngredient12;
String strIngredient13;
String strIngredient14;
String strIngredient15;
dynamic strIngredient16;
dynamic strIngredient17;
dynamic strIngredient18;
dynamic strIngredient19;
dynamic strIngredient20;
String strMeasure1;
String strMeasure2;
String strMeasure3;
String strMeasure4;
String strMeasure5;
String strMeasure6;
String strMeasure7;
String strMeasure8;
String strMeasure9;
String strMeasure10;
String strMeasure11;
String strMeasure12;
String strMeasure13;
String strMeasure14;
String strMeasure15;
dynamic strMeasure16;
dynamic strMeasure17;
dynamic strMeasure18;
dynamic strMeasure19;
dynamic strMeasure20;
dynamic strSource;
dynamic dateModified;
factory Meal.fromJson(Map<String, dynamic> json) => Meal(
idMeal: json["idMeal"] == null ? null : json["idMeal"],
strMeal: json["strMeal"] == null ? null : json["strMeal"],
strDrinkAlternate: json["strDrinkAlternate"],
strCategory: json["strCategory"] == null ? null : json["strCategory"],
strArea: json["strArea"] == null ? null : json["strArea"],
strInstructions:
json["strInstructions"] == null ? null : json["strInstructions"],
strMealThumb:
json["strMealThumb"] == null ? null : json["strMealThumb"],
strTags: json["strTags"] == null ? null : json["strTags"],
strYoutube: json["strYoutube"] == null ? null : json["strYoutube"],
strIngredient1:
json["strIngredient1"] == null ? null : json["strIngredient1"],
strIngredient2:
json["strIngredient2"] == null ? null : json["strIngredient2"],
strIngredient3:
json["strIngredient3"] == null ? null : json["strIngredient3"],
strIngredient4:
json["strIngredient4"] == null ? null : json["strIngredient4"],
strIngredient5:
json["strIngredient5"] == null ? null : json["strIngredient5"],
strIngredient6:
json["strIngredient6"] == null ? null : json["strIngredient6"],
strIngredient7:
json["strIngredient7"] == null ? null : json["strIngredient7"],
strIngredient8:
json["strIngredient8"] == null ? null : json["strIngredient8"],
strIngredient9:
json["strIngredient9"] == null ? null : json["strIngredient9"],
strIngredient10:
json["strIngredient10"] == null ? null : json["strIngredient10"],
strIngredient11:
json["strIngredient11"] == null ? null : json["strIngredient11"],
strIngredient12:
json["strIngredient12"] == null ? null : json["strIngredient12"],
strIngredient13:
json["strIngredient13"] == null ? null : json["strIngredient13"],
strIngredient14:
json["strIngredient14"] == null ? null : json["strIngredient14"],
strIngredient15:
json["strIngredient15"] == null ? null : json["strIngredient15"],
strIngredient16: json["strIngredient16"],
strIngredient17: json["strIngredient17"],
strIngredient18: json["strIngredient18"],
strIngredient19: json["strIngredient19"],
strIngredient20: json["strIngredient20"],
strMeasure1: json["strMeasure1"] == null ? null : json["strMeasure1"],
strMeasure2: json["strMeasure2"] == null ? null : json["strMeasure2"],
strMeasure3: json["strMeasure3"] == null ? null : json["strMeasure3"],
strMeasure4: json["strMeasure4"] == null ? null : json["strMeasure4"],
strMeasure5: json["strMeasure5"] == null ? null : json["strMeasure5"],
strMeasure6: json["strMeasure6"] == null ? null : json["strMeasure6"],
strMeasure7: json["strMeasure7"] == null ? null : json["strMeasure7"],
strMeasure8: json["strMeasure8"] == null ? null : json["strMeasure8"],
strMeasure9: json["strMeasure9"] == null ? null : json["strMeasure9"],
strMeasure10:
json["strMeasure10"] == null ? null : json["strMeasure10"],
strMeasure11:
json["strMeasure11"] == null ? null : json["strMeasure11"],
strMeasure12:
json["strMeasure12"] == null ? null : json["strMeasure12"],
strMeasure13:
json["strMeasure13"] == null ? null : json["strMeasure13"],
strMeasure14:
json["strMeasure14"] == null ? null : json["strMeasure14"],
strMeasure15:
json["strMeasure15"] == null ? null : json["strMeasure15"],
strMeasure16: json["strMeasure16"],
strMeasure17: json["strMeasure17"],
strMeasure18: json["strMeasure18"],
strMeasure19: json["strMeasure19"],
strMeasure20: json["strMeasure20"],
strSource: json["strSource"],
dateModified: json["dateModified"],
);
Map<String, dynamic> toJson() => {
"idMeal": idMeal == null ? null : idMeal,
"strMeal": strMeal == null ? null : strMeal,
"strDrinkAlternate": strDrinkAlternate,
"strCategory": strCategory == null ? null : strCategory,
"strArea": strArea == null ? null : strArea,
"strInstructions": strInstructions == null ? null : strInstructions,
"strMealThumb": strMealThumb == null ? null : strMealThumb,
"strTags": strTags == null ? null : strTags,
"strYoutube": strYoutube == null ? null : strYoutube,
"strIngredient1": strIngredient1 == null ? null : strIngredient1,
"strIngredient2": strIngredient2 == null ? null : strIngredient2,
"strIngredient3": strIngredient3 == null ? null : strIngredient3,
"strIngredient4": strIngredient4 == null ? null : strIngredient4,
"strIngredient5": strIngredient5 == null ? null : strIngredient5,
"strIngredient6": strIngredient6 == null ? null : strIngredient6,
"strIngredient7": strIngredient7 == null ? null : strIngredient7,
"strIngredient8": strIngredient8 == null ? null : strIngredient8,
"strIngredient9": strIngredient9 == null ? null : strIngredient9,
"strIngredient10": strIngredient10 == null ? null : strIngredient10,
"strIngredient11": strIngredient11 == null ? null : strIngredient11,
"strIngredient12": strIngredient12 == null ? null : strIngredient12,
"strIngredient13": strIngredient13 == null ? null : strIngredient13,
"strIngredient14": strIngredient14 == null ? null : strIngredient14,
"strIngredient15": strIngredient15 == null ? null : strIngredient15,
"strIngredient16": strIngredient16,
"strIngredient17": strIngredient17,
"strIngredient18": strIngredient18,
"strIngredient19": strIngredient19,
"strIngredient20": strIngredient20,
"strMeasure1": strMeasure1 == null ? null : strMeasure1,
"strMeasure2": strMeasure2 == null ? null : strMeasure2,
"strMeasure3": strMeasure3 == null ? null : strMeasure3,
"strMeasure4": strMeasure4 == null ? null : strMeasure4,
"strMeasure5": strMeasure5 == null ? null : strMeasure5,
"strMeasure6": strMeasure6 == null ? null : strMeasure6,
"strMeasure7": strMeasure7 == null ? null : strMeasure7,
"strMeasure8": strMeasure8 == null ? null : strMeasure8,
"strMeasure9": strMeasure9 == null ? null : strMeasure9,
"strMeasure10": strMeasure10 == null ? null : strMeasure10,
"strMeasure11": strMeasure11 == null ? null : strMeasure11,
"strMeasure12": strMeasure12 == null ? null : strMeasure12,
"strMeasure13": strMeasure13 == null ? null : strMeasure13,
"strMeasure14": strMeasure14 == null ? null : strMeasure14,
"strMeasure15": strMeasure15 == null ? null : strMeasure15,
"strMeasure16": strMeasure16,
"strMeasure17": strMeasure17,
"strMeasure18": strMeasure18,
"strMeasure19": strMeasure19,
"strMeasure20": strMeasure20,
"strSource": strSource,
"dateModified": dateModified,
};
}
class RemoteServices {
static var client = http.Client();
static Future<List<Meal>> fetchMealById(String id) async {
print(id);
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Payload payload = payloadFromJson(response.body);
//Meal meal = Meal.fromJson(json.decode(response.body));
print(payload.meals.length);
print(payload.meals);
return payload.meals;
} else {
throw Exception("Unable to Load");
}
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Function _future;
#override
void initState() {
_future = RemoteServices.fetchMealById;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future("yourId"),
builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
print(snapshot.data.runtimeType);
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[index].idMeal.toString()),
Spacer(),
Text(
snapshot.data[index].strCategory,
),
],
),
));
});
}
}
}));
}
}