I am trying to get data from API but having error - flutter

This is my model class and I am trying to get all the data but getting error and don't know why.
HomePageModel homePageModelFromJson(String str) => HomePageModel.fromJson(json.decode(str));
String homePageModelToJson(HomePageModel data) => json.encode(data.toJson());
class HomePageModel with ChangeNotifier {
HomePageModel({
this.data,
});
List<Datum>? data;
factory HomePageModel.fromJson(Map<String, dynamic> json) => HomePageModel(
data: List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
schoolid: json["schoolid"],
name: json["name"],
logo: json["logo"],
address: json["address"],
contact: json["contact"],
principalname: json["principalname"],
principalcontact: json["principalcontact"],
slogan: json["slogan"],
webAddress: json["web_address"] == null ? null : json["web_address"],
description: json["description"] == null ? null : json["description"],
email: json["email"],
pan: json["pan"],
establishedYear: json["established_year"],
);
Map<String, dynamic> toJson() => {
"schoolid": schoolid,
"name": name,
"logo": logo,
"address": address,
"contact": contact,
"principalname": principalname,
"principalcontact": principalcontact,
"slogan": slogan,
"web_address": webAddress == null ? null : webAddress,
"description": description == null ? null : description,
"email": email,
"pan": pan,
"established_year": establishedYear,
};
}
This is how I am trying to fetch data:
class HomePageModels with ChangeNotifier{
List<HomePageModel> _hItem = [];
List<HomePageModel> get hItem{
return [..._hItem];
}
Future<void> getHomeData(BuildContext context) async{
const url = "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try{
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
List<HomePageModel> loadedHomeData = [];
if(extractedData == null){
return;
}
if(response.statusCode == 200){
print(extractedData);
}
extractedData.forEach((element){
loadedHomeData.add(HomePageModel.fromJson(element));
});
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
}catch(e){
rethrow;
}
}
}
But I am getting error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'

The problem is the way you are trying to parse the data, you don't need to loop over every element to parse it, in your model just make it return a list type like this,
class HomePageModel with ChangeNotifier {
List<Datum>? data;
HomePageModel({this.data});
HomePageModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Datum>[];
json['data'].forEach((v) {
data!.add(new Datum.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
Datum.fromJson(Map<String, dynamic> json) {
schoolid = json["schoolid"];
name = json["name"];
logo = json["logo"];
address = json["address"];
contact = json["contact"];
principalname = json["principalname"];
principalcontact = json["principalcontact"];
slogan = json["slogan"];
webAddress = json["web_address"];
description = json["description"];
email = json["email"];
pan = json["pan"];
establishedYear = json["established_year"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['schoolid'] = this.schoolid;
data['name'] = this.name;
data['logo'] = this.logo;
data['address'] = this.address;
data['contact'] = this.contact;
data['principalname'] = this.principalname;
data['principalcontact'] = this.principalcontact;
data['slogan'] = this.slogan;
data['web_address'] = this.webAddress;
data['description'] = this.description;
data['email'] = this.email;
data['pan'] = this.pan;
data['established_year'] = this.establishedYear;
return data;
}
}
and in your view model you can just parse the extracted data from response.body like this,
class HomePageModels with ChangeNotifier {
HomePageModel? _hItem;
HomePageModel get hItem {
return _hItem!;
}
Future<void> getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-
4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
if (extractedData == null) {
return;
}
if (response.statusCode == 200) {
print(extractedData);
}
HomePageModel loadedHomeData =
HomePageModel.fromJson(extractedData);
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
} catch (e) {
rethrow;
}
}
}

getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final extractedData = json.decode(response.body);
List loadedHomeData = extractedData;
_hItem = loadedHomeData.map((e) => HomePageModel.fromJson(e)).toList();
}
notifyListeners();
return _hItem;
} catch (e) {
rethrow;
}
}

Related

Mapping a list inside another in flutter

I'm trying to map a list which has another list of objects but an error keep showing . Thank you for any help in advance
My Class
import 'Standing.dart';
class League {
String? country;
String? flag;
int? id;
String? logo;
String? name;
int? season;
List<List<Standing>>? standings;
League({this.country, this.flag, this.id, this.logo, this.name, this.season, this.standings});
factory League.fromJson(Map<String, dynamic> json) {
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: json['standings'] != null ? (json['standings'] as List).map((i) => List<Standing>.from(i)).toList() : [],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['country'] = country;
data['flag'] = flag;
data['id'] = id;
data['logo'] = logo;
data['name'] = name;
data['season'] = season;
data['standings'] = standings?.map((v) => List<Standing>.from(v)).toList();
return data;
}
}
Standings Class
import 'All.dart';
import 'Away.dart';
import 'Home.dart';
import 'Team.dart';
class Standing {
All? all;
Away? away;
String? form;
int? goalsDiff;
String? group;
Home? home;
int? points;
int? rank;
String? status;
Team? team;
String? update;
Standing({this.all, this.away, this.form, this.goalsDiff, this.group, this.home, this.points, this.rank, this.status, this.team, this.update});
factory Standing.fromJson(Map<String, dynamic> json) {
return Standing(
all: json['all'] != null ? All.fromJson(json['all']) : null,
away: json['away'] != null ? Away.fromJson(json['away']) : null,
form: json['form'],
goalsDiff: json['goalsDiff'],
group: json['group'],
home: json['home'] != null ? Home.fromJson(json['home']) : null,
points: json['points'],
rank: json['rank'],
status: json['status'],
team: json['team'] != null ? Team.fromJson(json['team']) : null,
update: json['update'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['form'] = this.form;
data['goalsDiff'] = this.goalsDiff;
data['group'] = this.group;
data['points'] = this.points;
data['rank'] = this.rank;
data['status'] = this.status;
data['update'] = this.update;
final all = this.all;
if (all != null) {
data['all'] = all.toJson();
}
final away = this.away;
if (away != null) {
data['away'] = away.toJson();
}
final home = this.home;
if (home != null) {
data['home'] = home.toJson();
}
final team = this.team;
if (team != null) {
data['team'] = team.toJson();
}
return data;
}
}
data parsing
Future<StModel?> getStandings(int leagueId , int season) async {
HttpWithMiddleware httpClient = HttpWithMiddleware.build(middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
]);
var fullUrl = "${Utils.BASE_URL}standings?league=$leagueId&season=$season";
var response = await httpClient.get(Uri.parse(fullUrl),headers: {
'x-rapidapi-host' : Utils.HOST,
'x-rapidapi-key' : Utils.KEY,
});
if(response.statusCode == 200){
var json = jsonDecode(response.body);
return StModel.fromJson(json);
} else {
return null;
}
}
Error
Change this:
factory League.fromJson(Map<String, dynamic> json) {
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: json['standings'] != null ? (json['standings'] as List).map((i) => List<Standing>.from(i)).toList() : [],
);
}
to:
factory League.fromJson(Map<String, dynamic> json) {
List<List<Standing>> _standings = [];
for (var element in json['league']['standings'] as List) {
List<Standing> temp = [];
for (var item in element) {
temp.add(Standing.fromJson(item));
}
_standings.add(temp);
}
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: _standings,
);
}
then use it like this:
if(response.statusCode == 200){
var json = jsonDecode(response.body);
return League.fromJson(json['response']);
} else {
return null;
}

FutureBuilder snapshot.hasData always return false

i'm new to learning darts and flutter i'm making code to display data with FutureBuilder, in console window i got the response i want, but the snapshot.hashData code always returns false
Myclass model
class ResponseDataBarang {
int? _kode;
String? _pesan;
List<Data>? _data;
ResponseDataBarang({int? kode, String? pesan, List<Data>? data}) {
if (kode != null) {
this._kode = kode;
}
if (pesan != null) {
this._pesan = pesan;
}
if (data != null) {
this._data = data;
}
}
int? get kode => _kode;
set kode(int? kode) => _kode = kode;
String? get pesan => _pesan;
set pesan(String? pesan) => _pesan = pesan;
List<Data>? get data => _data;
set data(List<Data>? data) => _data = data;
ResponseDataBarang.fromJson(Map<String, dynamic> json) {
_kode = json['kode'];
_pesan = json['pesan'];
if (json['data'] != null) {
_data = <Data>[];
json['data'].forEach((v) {
_data!.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['kode'] = this._kode;
data['pesan'] = this._pesan;
if (this._data != null) {
data['data'] = this._data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? _kdBrg;
String? _nmBrg;
Data(
{String? kdBrg,
String? nmBrg,
}) {
if (kdBrg != null) {
_kdBrg = kdBrg;
}
if (nmBrg != null) {
_nmBrg = nmBrg;
}
}
String? get kdBrg => _kdBrg;
set kdBrg(String? kdBrg) => _kdBrg = kdBrg;
String? get nmBrg => _nmBrg;
Data.fromJson(Map<String, dynamic> json) {
_kdBrg = json['KdBrg'];
_nmBrg = json['NmBrg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['KdBrg'] = _kdBrg;
data['NmBrg'] = _nmBrg;
return data;
}
}
My request
i am confused for the json format as generated what return value is suitable for my method request
Future<ResponseDataBarang> ambilDataBarang() async {
Dio apiClient=ApiClient().init();
final response=await apiClient.post('http://192.168.1.8/aplikasikasir/data_barang.php', data: FormData.fromMap(({
"NmUser":"T",
})));
return ResponseDataBarang.fromJson(response.data);
}
}
Response i got
{"kode":1,"pesan":"Data Tersedia","data":[{"KdBrg":"170164017","NmBrg":"ST PP HONGNIE SANDAL","Harga":"38000","Stock_Akhir":"0","Sat_1":"PT","Sat_2":"","Sat_3":"","Sat_4":"","Isi_2":"0","Isi_3":"0","Isi_4":"0","KdSupl":"","NmSupl":"","Ket1":""}]}

Receive data from API using Flutter

I work with flutter not so long and i don't know how to retrieve data as same as I described below.
I create an app with API. I received all data except Gallery images, program, additionalInfo.
Can anyone explain to me how I can retrieve gallery images, program and additionalInfo from API?
If you can write code snippets which I can use. Thanks.
'https://tripvenue.ru/api/v1/experiences/448'
import 'dart:convert';
ExperiencesByCityId experiencesByCityIdFromJson(String str) =>
ExperiencesByCityId.fromJson(json.decode(str));
String experiencesByCityIdToJson(ExperiencesByCityId data) =>
json.encode(data.toJson());
class ExperiencesByCityId {
ExperiencesByCityId({
this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax,
});
int id;
String title;
String promoText;
City country;
City city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
factory ExperiencesByCityId.fromJson(Map<String, dynamic> json) =>
ExperiencesByCityId(
id: json["id"],
title: json["title"],
promoText: json["promo_text"],
country: City.fromJson(json["country"]),
city: City.fromJson(json["city"]),
mainPhoto: MainPhoto.fromJson(json["main_photo"]),
type: json["type"],
languages: List<String>.from(json["languages"].map((x) => x)),
instantBooking: json["instant_booking"],
duration: json["duration"],
votesCount: json["votes_count"],
votesAvg: json["votes_avg"],
url: json["url"],
pricing: Pricing.fromJson(json["pricing"]),
teaserText: json["teaser_text"],
description: json["description"],
program:
List<Program>.from(json["program"].map((x) => Program.fromJson(x))),
additionalInfo:
List<String>.from(json["additional_info"].map((x) => x)),
gallery:
List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
guestsMin: json["guests_min"],
guestsMax: json["guests_max"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"promo_text": promoText,
"country": country.toJson(),
"city": city.toJson(),
"main_photo": mainPhoto.toJson(),
"type": type,
"languages": List<dynamic>.from(languages.map((x) => x)),
"instant_booking": instantBooking,
"duration": duration,
"votes_count": votesCount,
"votes_avg": votesAvg,
"url": url,
"pricing": pricing.toJson(),
"teaser_text": teaserText,
"description": description,
"program": List<dynamic>.from(program.map((x) => x.toJson())),
"additional_info": List<dynamic>.from(additionalInfo.map((x) => x)),
"gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
"guests_min": guestsMin,
"guests_max": guestsMax,
};
}
class City {
City({
this.id,
this.name,
});
int id;
String name;
factory City.fromJson(Map<String, dynamic> json) => City(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class Gallery {
Gallery({
this.fid,
this.uri,
this.url,
});
int fid;
String uri;
String url;
factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
fid: json["fid"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"fid": fid,
"uri": uri,
"url": url,
};
}
class MainPhoto {
MainPhoto({
this.id,
this.uri,
this.url,
});
int id;
String uri;
String url;
factory MainPhoto.fromJson(Map<String, dynamic> json) => MainPhoto(
id: json["id"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"id": id,
"uri": uri,
"url": url,
};
}
class Pricing {
Pricing({
this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax,
});
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
factory Pricing.fromJson(Map<String, dynamic> json) => Pricing(
type: json["type"],
amount: json["amount"],
currency: json["currency"],
formatted: json["formatted"],
groupSizeMin: json["group_size_min"],
groupSizeMax: json["group_size_max"],
);
Map<String, dynamic> toJson() => {
"type": type,
"amount": amount,
"currency": currency,
"formatted": formatted,
"group_size_min": groupSizeMin,
"group_size_max": groupSizeMax,
};
}
class Program {
Program({
this.first,
this.second,
});
String first;
Second second;
factory Program.fromJson(Map<String, dynamic> json) => Program(
first: json["first"],
second: secondValues.map[json["second"]],
);
Map<String, dynamic> toJson() => {
"first": first,
"second": secondValues.reverse[second],
};
}
enum Second { EMPTY, SECOND, PURPLE }
final secondValues = EnumValues({
"": Second.EMPTY,
"по возможности посмотрим их на закате": Second.PURPLE,
"здесь вы сделаете классные фото на заброшке": Second.SECOND
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
You can generate your Response class from https://jsontodart.com
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: TextButton(
onPressed: () async {
var response = await http.get(
Uri.parse('https://tripvenue.ru/api/v1/experiences/448'));
var body = response.body;
Response myResponse = Response.fromJson(json.decode(body));
print(myResponse.gallery.first.url);
},
child: Text(
"press",
),
),
)));
}
}
class Response {
int id;
String title;
String promoText;
Country country;
Country city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
Response(
{this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax});
Response.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
promoText = json['promo_text'];
country =
json['country'] != null ? new Country.fromJson(json['country']) : null;
city = json['city'] != null ? new Country.fromJson(json['city']) : null;
mainPhoto = json['main_photo'] != null
? new MainPhoto.fromJson(json['main_photo'])
: null;
type = json['type'];
languages = json['languages'].cast<String>();
instantBooking = json['instant_booking'];
duration = json['duration'];
votesCount = json['votes_count'];
votesAvg = json['votes_avg'];
url = json['url'];
pricing =
json['pricing'] != null ? new Pricing.fromJson(json['pricing']) : null;
teaserText = json['teaser_text'];
description = json['description'];
if (json['program'] != null) {
program = <Program>[];
json['program'].forEach((v) {
program.add(new Program.fromJson(v));
});
}
additionalInfo = json['additional_info'].cast<String>();
if (json['gallery'] != null) {
gallery = <Gallery>[];
json['gallery'].forEach((v) {
gallery.add(new Gallery.fromJson(v));
});
}
guestsMin = json['guests_min'];
guestsMax = json['guests_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['promo_text'] = this.promoText;
if (this.country != null) {
data['country'] = this.country.toJson();
}
if (this.city != null) {
data['city'] = this.city.toJson();
}
if (this.mainPhoto != null) {
data['main_photo'] = this.mainPhoto.toJson();
}
data['type'] = this.type;
data['languages'] = this.languages;
data['instant_booking'] = this.instantBooking;
data['duration'] = this.duration;
data['votes_count'] = this.votesCount;
data['votes_avg'] = this.votesAvg;
data['url'] = this.url;
if (this.pricing != null) {
data['pricing'] = this.pricing.toJson();
}
data['teaser_text'] = this.teaserText;
data['description'] = this.description;
if (this.program != null) {
data['program'] = this.program.map((v) => v.toJson()).toList();
}
data['additional_info'] = this.additionalInfo;
if (this.gallery != null) {
data['gallery'] = this.gallery.map((v) => v.toJson()).toList();
}
data['guests_min'] = this.guestsMin;
data['guests_max'] = this.guestsMax;
return data;
}
}
class Country {
int id;
String name;
Country({this.id, this.name});
Country.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class MainPhoto {
int id;
String uri;
String url;
MainPhoto({this.id, this.uri, this.url});
MainPhoto.fromJson(Map<String, dynamic> json) {
id = json['id'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}
class Pricing {
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
Pricing(
{this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax});
Pricing.fromJson(Map<String, dynamic> json) {
type = json['type'];
amount = json['amount'];
currency = json['currency'];
formatted = json['formatted'];
groupSizeMin = json['group_size_min'];
groupSizeMax = json['group_size_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['amount'] = this.amount;
data['currency'] = this.currency;
data['formatted'] = this.formatted;
data['group_size_min'] = this.groupSizeMin;
data['group_size_max'] = this.groupSizeMax;
return data;
}
}
class Program {
String first;
String second;
Program({this.first, this.second});
Program.fromJson(Map<String, dynamic> json) {
first = json['first'];
second = json['second'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['first'] = this.first;
data['second'] = this.second;
return data;
}
}
class Gallery {
int fid;
String uri;
String url;
Gallery({this.fid, this.uri, this.url});
Gallery.fromJson(Map<String, dynamic> json) {
fid = json['fid'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['fid'] = this.fid;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}

Flutter - 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

Flutter Error - List' is not a subtype of type 'Map<String, dynamic>. Am getting this error decoding json API response in flutter. i believe the problem is within the UserLogin Model but i don't know to handle it. How do you map the json data to the response data correctly.
The model class
class UserLogin {
bool success;
int statusCode;
String code;
String message;
List<Data> data;
UserLogin({
this.code,
this.success,
this.message,
this.statusCode,
this.data,
});
UserLogin.fromJson(Map<String, dynamic>json){
success = json['success'];
statusCode = json['statusCode'];
code = json['code'];
message = json['message'];
//data = json['data'] != null ? new Data.fromJson(json['data']) : null;
if(json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v){
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['statuCode'] = this.statusCode;
data['code'] = this.code;
data['message'] = this.message;
if(this.data != null) {
data['data'] = this.data.toList();
}
return data;
}
#override toString() => this.toJson().toString();
}
class Data {
String token;
int id;
String email;
String nicename;
String firstname;
String lastname;
String displayName;
Data(
{this.token,
this.id,
this.email,
this.nicename,
this.firstname,
this.lastname,
this.displayName});
Data.fromJson(Map<String, dynamic> json){
token = json['token'];
id = json['id'];
email = json['email'];
nicename = json['nicename'];
firstname = json['firstname'];
displayName = json['displayName'];
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['token'] = this.token;
data['id'] = this.id;
data['email'] = this.email;
data['nicename'] = this.nicename;
data['firstname'] = this.firstname;
data['displayName'] = this.displayName;
return data;
}
}
The async function calling the api
Future<UserLogin> loginCustomer(String username, String password ) async {
//List<UserLogin> model = new List<UserLogin>();
UserLogin model;
try {
var response = await Dio().post(
Config.tokenURL,
data: {
"username" : username,
"password" : password,
},
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
},
),
);
if(response.statusCode == 200) {
print(response.data);
model = UserLogin.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return model;
}

Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' in the Data model

I am getting this Error Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' decoding a json from an API, I believe the problem may be from the Data class in the model but i don't know how to solve it.
The model class
class UserLogin {
bool success;
int statusCode;
String code;
String message;
List<Data> data;
UserLogin({
this.code,
this.success,
this.message,
this.statusCode,
this.data,
});
UserLogin.fromJson(Map<String, dynamic>json){
success = json['success'];
statusCode = json['statusCode'];
code = json['code'];
message = json['message'];
//data = json['data'] != null ? new Data.fromJson(json['data']) : null;
if(json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v){
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['statuCode'] = this.statusCode;
data['code'] = this.code;
data['message'] = this.message;
if(this.data != null) {
data['data'] = this.data.toList();
}
return data;
}
#override toString() => this.toJson().toString();
}
class Data {
String token;
int id;
String email;
String nicename;
String firstname;
String lastname;
String displayName;
Data(
{this.token,
this.id,
this.email,
this.nicename,
this.firstname,
this.lastname,
this.displayName});
Data.fromJson(Map<String, dynamic> json){
token = json['token'];
id = json['id'];
email = json['email'];
nicename = json['nicename'];
firstname = json['firstname'];
displayName = json['displayName'];
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['token'] = this.token;
data['id'] = this.id;
data['email'] = this.email;
data['nicename'] = this.nicename;
data['firstname'] = this.firstname;
data['displayName'] = this.displayName;
return data;
}
}
The async function calling the api
Future<UserLogin> loginCustomer(String username, String password ) async {
//List<UserLogin> model = new List<UserLogin>();
UserLogin model;
try {
var response = await Dio().post(
Config.tokenURL,
data: {
"username" : username,
"password" : password,
},
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
},
),
);
if(response.statusCode == 200) {
print(response.data);
model = UserLogin.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return model;
}
Response from Api
{success: true, statusCode: 200, code: jwt_auth_valid_credential, message: Credential is valid, data: {token:***, id: 1, email: ***, nicename: ***, firstName: ***, lastName: ***, displayName: ****}}
Updated Code
class UserLogin {
bool success;
int statusCode;
String code;
String message;
Data data;
UserLogin({
this.code,
this.success,
this.message,
this.statusCode,
this.data,
});
UserLogin.fromJson(Map<String, dynamic>json){
success = json['success'];
statusCode = json['statusCode'];
code = json['code'];
message = json['message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['statuCode'] = this.statusCode;
data['code'] = this.code;
data['message'] = this.message;
if(this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
#override toString() => this.toJson().toString();
}
class Data {
String token;
int id;
String email;
String nicename;
String firstname;
String lastname;
String displayName;
Data(
{this.token,
this.id,
this.email,
this.nicename,
this.firstname,
this.lastname,
this.displayName});
Data.fromJson(Map<String, dynamic> json){
token = json['token'];
id = json['id'];
email = json['email'];
nicename = json['nicename'];
firstname = json['firstname'];
displayName = json['displayName'];
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['token'] = this.token;
data['id'] = this.id;
data['email'] = this.email;
data['nicename'] = this.nicename;
data['firstname'] = this.firstname;
data['displayName'] = this.displayName;
return data;
}
}
Based on the response.data, your data is an object, but you defined it as List in UserLogin model class, which is wrong.
The correct should beData data;