Related
I have 2 things I want to compare and return a list of Strings for each of the matching Ids with the corresponding names. Example: I have a list of "genre_ids": [16, 878, 28] from a movie, and from another API I get a list of objects with id and name of the genres, { "id": 878, "name": "Science Fiction" }. Now I want to compare the list of genre_ids with the list of objects with ids and names and return a List of names with all the matching Ids. How do I do that? I tried using the .where() option but failed miserably.
JSON from genre list:
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 10749,
"name": "Romance"
},
{
"id": 878,
"name": "Science Fiction"
},
]
}
JSON from movie list:
"results": [
{
"adult": false,
"genre_ids": [
16,
878,
28
],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
},
]
Both models from the APIs:
class Movies {
int? id;
String? title;
String? overview;
List<dynamic>? genreIds;
dynamic voteAverage;
String? posterPath;
Movies({
this.id,
this.title,
this.overview,
this.genreIds,
this.voteAverage,
this.posterPath,
});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
overview = json['overview'];
genreIds = json['genre_ids'].toList();
voteAverage = json['vote_average'];
posterPath = json['poster_path'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['title'] = title;
data['overview'] = overview;
data['vote_average'] = voteAverage;
data['genre_ids'] = genreIds;
data['poster_path'] = posterPath;
return data;
}
}
class Genres {
int? id;
String? name;
Genres({
this.id,
this.name,
});
Genres.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'] as String;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['name'] = name;
return data;
}
}
API calls:
Future<List<Movies?>> getAllMovies() async {
Response response = await Dio().get(Contants().moviesUrl);
return (response.data['results'] as List).map((movies) {
return Movies.fromJson(genres);
}).toList();
}
Future<List<Genres?>> getAllGenres() async {
Response response = await Dio().get(Contants().genresUrl);
return (response.data['genres'] as List).map((genres) {
return Genres.fromJson(genres);
}).toList();
}
Future builder:
FutureBuilder(
future: Future.wait([
RepositoryFromAPItoDB().gettAllMovies(),
RepositoryFromAPItoDB().getAllGenres()
]),
builder:
(BuildContext context, AsyncSnapshot<List<dynamic>?> snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data?[0].length,
itemBuilder: (BuildContext context, int index) {
return MoviesListTile(
title: snapshot.data?[0][index].title,
voteAverage: snapshot.data?[0][index].voteAverage,
description: snapshot.data?[0][index].overview,
posterPath: snapshot.data?[0][index].posterPath,
genreIds: snapshot.data?[0][index].genreIds,
genres: ['drama', 'somehting'],
);
},
);
}
},
),
Requested output of names from the list:
Widget getTextWidgets(List<String?> strings) {
return Row(
children: strings
.map((item) => Container(
child: Text(
item!,
),
),
),
)
.toList());
}
Any form of help is appreciated.
Is this what you wanted?
void main() {
Map<String, dynamic> genres = {
"genres": [
{"id": 28, "name": "Action"},
{"id": 12, "name": "Adventure"},
{"id": 16, "name": "Animation"},
{"id": 35, "name": "Comedy"},
{"id": 10749, "name": "Romance"},
{"id": 878, "name": "Science Fiction"},
]
};
Map<String, dynamic> movie = {
"adult": false,
"genre_ids": [16, 878, 28],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
};
print(getGenres(movie, genres["genres"]));
}
List getGenres(Map movie, List genres) {
final Set movieGenreIds = Set.from(movie["genre_ids"]);
return genres
.where((g) => movieGenreIds.contains(g["id"]))
.map((g) => g["name"])
.toList();
}
The output:
[Action, Animation, Science Fiction]
Edit, using the models you provided.
List getGenres(Movie movie, List<Genre> genres) {
final Set movieGenreIds = Set.from(movie.genreIds);
return genres
.where((g) => movieGenreIds.contains(g.id))
.map((g) => g.name)
.toList();
}
I am trying to map a json list in my application using JSON Serializable. But I am not able to map it.
Following is the response from the API:
{
"code": 200,
"message": "Countries Lists",
"count": 250,
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 2,
"name": "Aland Islands"
},
{
"id": 3,
"name": "Albania"
},
{
"id": 4,
"name": "Algeria"
},
{
"id": 5,
"name": "American Samoa"
},
{
"id": 6,
"name": "Andorra"
},
{
"id": 7,
"name": "Angola"
},
{
"id": 8,
"name": "Anguilla"
},
{
"id": 9,
"name": "Antarctica"
},
{
"id": 10,
"name": "Antigua And Barbuda"
},
{
"id": 11,
"name": "Argentina"
},
{
"id": 12,
"name": "Armenia"
},
{
"id": 13,
"name": "Aruba"
},
{
"id": 14,
"name": "Australia"
},
{
"id": 15,
"name": "Austria"
},
{
"id": 16,
"name": "Azerbaijan"
},
{
"id": 17,
"name": "Bahamas The"
},
{
"id": 18,
"name": "Bahrain"
},
{
"id": 19,
"name": "Bangladesh"
},
{
"id": 20,
"name": "Barbados"
}
]
}
Following is my response file:
#JsonSerializable()
class BaseResponse {
#JsonKey(name: "code")
int? status;
#JsonKey(name: "message")
String? message;
}
#JsonSerializable(explicitToJson: true)
class AllCountryResponse extends BaseResponse {
#JsonKey(name: "data")
List<CountryResponse> data;
AllCountryResponse(this.data);
//from JSON
factory AllCountryResponse.fromJson(Map<String, dynamic> json) =>
_$AllCountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$AllCountryResponseToJson(this);
}
#JsonSerializable()
class CountryResponse {
#JsonKey(name: "id")
String? id;
#JsonKey(name: "name")
String? name;
CountryResponse(this.id, this.name);
//from JSON
factory CountryResponse.fromJson(Map<String, dynamic> json) =>
_$CountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$CountryResponseToJson(this);
}
I am able to generate the responses.g dart file.
Following is my mapper class file:
class Countries {
String id,name;
Countries(this.id,this.name);
}
class AllCountries{
List<Countries> countries;
AllCountries(this.countries);
}
extension CountryResponseMapper on CountryResponse? {
Countries toDomain() {
return Countries(
this?.id.orEmpty() ?? EMPTY, this?.name.orEmpty() ?? EMPTY);
}
}
extension AllCountriesResponseMapper on AllCountryResponse? {
AllCountries toDomain() {
return AllCountries(this?.data.map((e) => e.toDomain()).toList() ?? []);
}
}
Once I run my api I do get 200 status while using my bio, but after that it shows me the default error I have set, i.e. "Something went wrong". Which means there is an issue in mapping the response.
Can someone help me with mapping this list please?
This code should work.
This code is generated by a very small and simple script (which was written in a few minutes).
class Response {
Response(
{required this.code,
required this.message,
required this.count,
required this.data});
factory Response.fromJson(Map json) {
return Response(
code: json['code'] as int?,
message: json['message'] as String?,
count: json['count'] as int?,
data: json['data'] == null
? []
: (json['data'] as List).map((e) => Data.fromJson(e as Map)).toList(),
);
}
final int? code;
final String? message;
final int? count;
final List<Data> data;
static List<Response> fromJsonList(List json) {
return json.map((e) => Response.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'code': code,
'message': message,
'count': count,
'data': data.map((e) => e.toJson()).toList(),
};
}
static List<Map<String, dynamic>> toJsonList(List<Response> list) {
return list.map((e) => e.toJson()).toList();
}
}
class Data {
Data({required this.id, required this.name});
factory Data.fromJson(Map json) {
return Data(
id: json['id'] == null ? 0 : json['id'] as int,
name: json['name'] == null ? '' : json['name'] as String,
);
}
final int id;
final String name;
static List<Data> fromJsonList(List json) {
return json.map((e) => Data.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
};
}
static List<Map<String, dynamic>> toJsonList(List<Data> list) {
return list.map((e) => e.toJson()).toList();
}
}
Code generation script:
import 'dart:io';
import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';
void main() {
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);
final values = {
'classes': classesCode,
};
var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}
const _classes = r'''
Response:
fields:
code: int?
message: String?
count: int?
data: List<Data>
Data:
fields:
id: int
name: String
''';
const _template = r'''
{{classes}}
''';
my json=
{
"result": {
"name": "json1",
"pages": [{
"zones": [{
"title": "title1"
},
{
"title": "title2"
}],
"id": 4
},
{
"zones": [{
"title": "title3"
},
{
"title": "title4"
}],
"id": 12
}],
"creatorUserName": "admin",
"id": 2
}
}
futurebuilder code
List post = snapshot.data["result"]["pages"];
return new Stack(
children: post.where((val) => val["id"] == 4).map((post) {
for (var item in post['zones']) {
print("title "+ item['title']);
Container(
child: Text(item["title"]),
); //Container
}
}).toList(),
); //Stack
Error code: Stack's children must not contain any null values, but a null value was found at index 0
enter image description here
help how can to build an algorithms
if get id = 4 zones -> Text(title1), Text(title2),
else id empty zones -> Text(title1), Text(title2), zones -> Text(title3), Text(title4),
Try
List post = snapshots.data["result"]["pages"];
First Make a model class for your JSON response using this amazing webpage, after that you can easily. call the needed data
import 'dart:convert';
YourModelClassName yourModelClassNameFromJson(String str) => YourModelClassName.fromJson(json.decode(str));
String yourModelClassNameToJson(YourModelClassName data) => json.encode(data.toJson());
class YourModelClassName {
Result result;
YourModelClassName({
this.result,
});
factory YourModelClassName.fromJson(Map<String, dynamic> json) => YourModelClassName(
result: Result.fromJson(json["result"]),
);
Map<String, dynamic> toJson() => {
"result": result.toJson(),
};
}
class Result {
String name;
List<Page> pages;
String creatorUserName;
int id;
Result({
this.name,
this.pages,
this.creatorUserName,
this.id,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
name: json["name"],
pages: List<Page>.from(json["pages"].map((x) => Page.fromJson(x))),
creatorUserName: json["creatorUserName"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"pages": List<dynamic>.from(pages.map((x) => x.toJson())),
"creatorUserName": creatorUserName,
"id": id,
};
}
class Page {
List<Zone> zones;
int id;
Page({
this.zones,
this.id,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
zones: List<Zone>.from(json["zones"].map((x) => Zone.fromJson(x))),
id: json["id"],
);
Map<String, dynamic> toJson() => {
"zones": List<dynamic>.from(zones.map((x) => x.toJson())),
"id": id,
};
}
class Zone {
String title;
Zone({
this.title,
});
factory Zone.fromJson(Map<String, dynamic> json) => Zone(
title: json["title"],
);
Map<String, dynamic> toJson() => {
"title": title,
};
}
I have a json object here -
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "cciigcigc",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
I want to fetch it based on the ["data"]["status"] parameter; if the status is false, return a seperate list and if the status is true, return another list. I have tried to modify my current fetch method this way -
Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false
List<Post> statusComplete;
List<Post> statusInComplete;
String link = baseURL + fetchTodoByDate;
// print("printing from get task = $setter");
Stopwatch stopwatchbefore = new Stopwatch()..start();
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});
print('fetch executed in ${stopwatchbefore.elapsed}');
if (res.statusCode == 200) {
Stopwatch stopwatchafter = new Stopwatch()
..start();
var data = json.decode(res.body);
var rest = data["data"] as List;
if(identifier == true){
statusComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusComplete;
}else if(identifier == false){
statusInComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusInComplete;
}
print('statuscode executed in ${stopwatchafter.elapsed}');
Future.delayed(Duration(seconds: 5));
}
// print("List Size: ${list.length}");
}
This is the first time I am trying to fetch and separate the data this way. I have tried to look at some tutorials but none seemed to be satisfying my case.
Could i get some suggestion on how to fetch the data and then separate it based on a parameter?
check out the example below which will give the basic idea how the flow works.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final yourData = dataFromJson(jsonString);
dataList = yourData.data;
var statusComplete = dataList.where((i) => i.status == true).toList();
for (int i = 0; i < statusComplete.length; i++) {
print('This is the list for true status :${statusComplete[i].title}');
}
var statusInComplete = dataList.where((i) => i.status == false).toList();
print(statusInComplete[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(dataList[index].status.toString());
}),
)),
);
}
}
below is the model class
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
String error;
String message;
List<Datum> data;
Data({
this.error,
this.message,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
and this is the json that you specified
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "first",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "second",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "third",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
Try this model class
import 'dart:convert';
Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
class Jsonmodel {
String error;
String message;
List<Datum> data;
Jsonmodel({
this.error,
this.message,
this.data,
});
factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
use like this
var res = await http.post(Uri.encodeFull(link), headers: {"Accept":
"application/json", }, body: {"date" : setter.toString()});
Jsonmodel modeldata = jsonmodelFromJson(res);
// do your stuff
modeldata.data.foreach((data){
if(data.status){
//do your stuff
}else{
//do your stuff
}
});
The error says it cannot create ApplicableFlight there is a problem onFlightSegmentReference List dynamic is not a subtype of type 'Map String, dynamic
This is where json.decode and fromJson are used
var map = json.decode(response.body) as Map<String, dynamic>;
ResponseGate responseGate = new ResponseGate.fromJson(map);
this is the snip of the output from json.decode
..,ApplicableFlight: {FlightReferences: F1,FlightSegmentReference: {ref: 0199,ClassOfService: {refs:ABCD,Code: {SeatsLeft: 6,content: Z},MarketingName:world}},OriginDestinationReferences:FF},
response.body look like bellow:
{ ..,
{
"ApplicableFlight": {
"FlightReferences": "F1",
"FlightSegmentReference": {
"ref": "0199",
"ClassOfService": {
"refs": "FBCODE1ADT",
"Code": {
"SeatsLeft": 7,
"content": "Z"
},
"MarketingName": "world"
}
},
"OriginDestinationReferences": "FF"
}
},}
This is where the objects are defined and ResponseGate.fromJson(map) looking for
x.dart
#JsonSerializable()
class ResponseGate {
#JsonKey(name: "Offer")
List<Offer> offer;
ResponseGate(this.offer);
factory ResponseGate.fromJson(Map<String, dynamic> json) =>
_$ResponseGateFromJson(json);
}
#JsonSerializable()
class Offer {
#JsonKey(name: "PricedOffer")
PricedOffer pricedOffer;
Offer(this.pricedOffer);
factory Offer.fromJson(Map<String, dynamic> json) =>
_$OfferFromJson(json);
}
#JsonSerializable()
class PricedOffer {
#JsonKey(name: "Associations")
List<Associates> listOfAssociations;
PricedOffer(this.listOfAssociations);
factory PricedOffer.fromJson(Map<String, dynamic> json) =>
_$PricedOfferFromJson(json);
}
#JsonSerializable()
class Associates {
#JsonKey(name: "ApplicableFlight")
ApplicableFlight applicableFlight;
Associates(this.applicableFlight);
factory Associates.fromJson(Map<String, dynamic> json) =>
_$AssociatesFromJson(json);
}
#JsonSerializable()
class ApplicableFlight {
#JsonKey(name: "FlightReferences")
var flightReference;
#JsonKey(name: "FlightSegmentReference")
FlightSegmentReference flightSegmentReference;
#JsonKey(name: "OriginDestinationReferences")
var originDestinationReferences;
ApplicableFlight(this.flightReference, this.flightSegmentReference,
this.originDestinationReferences);
factory ApplicableFlight.fromJson(Map<String, dynamic> json) =>
_$ApplicableFlightFromJson(json);
}
#JsonSerializable()
class FlightSegmentReference {
#JsonKey(name: "ref")
var ref;
#JsonKey(name: "ClassOfService")
ClassOfService classOfService;
FlightSegmentReference(this.ref, this.classOfService);
factory FlightSegmentReference.fromJson(Map<String, dynamic> json) =>
_$FlightSegmentReferenceFromJson(json);
}
#JsonSerializable()
class ClassOfService {
#JsonKey(name: "refs")
var refs;
#JsonKey(name: "Code")
Code code;
#JsonKey(name: "MarketingName")
var marketingName;
ClassOfService(this.refs, this.code, this.marketingName);
factory ClassOfService.fromJson(Map<String, dynamic> json) =>
_$ClassOfServiceFromJson(json);
}
#JsonSerializable()
class Code {
#JsonKey(name: "SeatsLeft")
var seatLeft;
#JsonKey(name: "content")
var content;
Code(this.seatLeft, this.content);
factory Code.fromJson(Map<String, dynamic> json) => _$CodeFromJson(json);
}
x.g.dart
ApplicableFlight _$ApplicableFlightFromJson(Map<String, dynamic> json)
{
return $checkedNew('ApplicableFlight', json, () {
$checkKeys(json, allowedKeys: const [
'FlightReferences',
'FlightSegmentReference',
'OriginDestinationReferences'
]);
final val = ApplicableFlight(
$checkedConvert(json, 'FlightReferences', (v) => v),
$checkedConvert(
json,
'FlightSegmentReference',
(v) => v == null
? null
: FlightSegmentReference.fromJson(v as Map<String, dynamic>)),
$checkedConvert(json, 'OriginDestinationReferences', (v) => v));
return val;
}, fieldKeyMap: const {
'flightReference': 'FlightReferences',
'flightSegmentReference': 'FlightSegmentReference',
'originDestinationReferences': 'OriginDestinationReferences'
});
}
FlightSegmentReference _$FlightSegmentReferenceFromJson(
Map<String, dynamic> json) {
return $checkedNew('FlightSegmentReference', json, () {
$checkKeys(json, allowedKeys: const ['ref', 'ClassOfService']);
final val = FlightSegmentReference(
$checkedConvert(json, 'ref', (v) => v),
$checkedConvert(
json,
'ClassOfService',
(v) => v == null
? null
: ClassOfService.fromJson(v as Map<String, dynamic>)));
return val;
}, fieldKeyMap: const {'classOfService': 'ClassOfService'});
}
ClassOfService _$ClassOfServiceFromJson(Map<String, dynamic> json) {
return $checkedNew('ClassOfService', json, () {
$checkKeys(json, allowedKeys: const ['refs', 'Code', 'MarketingName']);
final val = ClassOfService(
$checkedConvert(json, 'refs', (v) => v),
$checkedConvert(json, 'Code',
(v) => v == null ? null : Code.fromJson(v as Map<String, dynamic>)),
$checkedConvert(json, 'MarketingName', (v) => v));
return val;
}, fieldKeyMap: const {'code': 'Code', 'marketingName': 'MarketingName'});
}
Code _$CodeFromJson(Map<String, dynamic> json) {
return $checkedNew('Code', json, () {
$checkKeys(json, allowedKeys: const ['SeatsLeft', 'content']);
final val = Code($checkedConvert(json, 'SeatsLeft', (v) => v),
$checkedConvert(json, 'content', (v) => v));
return val;
}, fieldKeyMap: const {'seatLeft': 'SeatsLeft'});
}
Updated
I have looked the api response and I have found that FlightSegmentReference comes in two different ways as bellow shows. How can I design such a format?
{
"Offer": [
{
"PricedOffer": {
"Associations": [
{
"ApplicableFlight": {
"FlightReferences": "Flight1",
"FlightSegmentReference": {
"ref": "99",
"ClassOfService": {
"refs": "ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": " World"
}
},
"OriginDestinationReferences": "OD1"
}
},
{
"ApplicableFlight": {
"FlightReferences": "Flight11",
"FlightSegmentReference": {
"ref": "BA0138",
"ClassOfService": {
"refs": "FBCODE1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "Club World"
}
},
"OriginDestinationReferences": "OD2"
}
}
]
}
},
{
"PricedOffer": {
"Associations": [
{
"ApplicableFlight": {
"FlightReferences": "Fl",
"FlightSegmentReference": [
{
"ref": "02",
"ClassOfService": {
"refs": "FBCODE2ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "Club World"
}
},
{
"ref": "58",
"ClassOfService": {
"refs": "1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "B"
}
}
],
"OriginDestinationReferences": "1"
}
},
{
"ApplicableFlight": {
"FlightReferences": "Fl11",
"FlightSegmentReference": {
"ref": "8",
"ClassOfService": {
"refs": "E1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "orld"
}
},
"OriginDestinationReferences": "O"
}
}
]
}
}
]}
List<dynamic> areas = new List();
areas = json.decode(response.body);
String _mySelection1;
Container(
height: 50,
child: DropdownButton<String>(
isExpanded: true,
isDense: true,
hint: new Text("Select Location"),
value: _mySelection1,
onChanged:(String newValue) {
setState(() {
_mySelection1 = newValue;
});
print (_mySelection1);
},
items: areas.map((map){
return DropdownMenuItem<String>(
value: map["area_id"],
child: Text(
map["name"],
),
);
}).toList(),
),
),
here is an example of solution to these kind of problem.. my json also receives Mam response. but i handled it by this way.. hope this example will help you. here is my response.
[{"id":"1","name":"Dermatology"},{"id":"2","name":"Cancer of Female Reproductive System"},{"id":"3","name":"Cardiology"},{"id":"4","name":"Dentistry"},{"id":"5","name":"Allergy & Immunology"},{"id":"6","name":"Anesthesia"},{"id":"7","name":"Colorectal Surgery"},{"id":"8","name":"Endocrinology (Diabetes, Hormones, Thyroid, etc.)"},{"id":"9","name":"ENT (Ear, Nose & Throat, Otorhinolaryngology)"},{"id":"10","name":"Gastroenterology (Stomach, Pancreas and Intestine)"},{"id":"11","name":"General Physician"}]
its in the error message Map for List you need probably List
than it matches and thus can be a subtype