Related
I have following model
import 'dart:convert';
ModelDevices modelDevicesFromJson(String str) =>
ModelDevices.fromJson(json.decode(str));
String modelDevicesToJson(ModelDevices data) =>
json.encode(data.toJson());
class ModelDevices {
ModelDevices({
required this.status,
required this.message,
required this.data,
});
String status;
String message;
List<BtData> data;
factory ModelDevices.fromJson(Map<String, dynamic> json) =>
ModelDevices(
status: json["status"],
message: json["message"],
data: List<BtData>.from(json["data"].map((x) => BtData.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class BtData {
BtData({
required this.id,
required this.name,
required this.serialNumber,
required this.created,
required this.lastEdited,
required this.description,
required this.ownerId,
required this.dataId,
required this.lastKnownCoordinates,
required this.dateOfCoordinates,
required this.lastDistance,
});
String id;
String name;
String serialNumber;
String created;
String lastEdited;
String description;
String ownerId;
String dataId;
String lastKnownCoordinates;
String dateOfCoordinates;
String lastDistance;
factory BtData.fromJson(Map<String, dynamic> json) => BtData(
id: json["id"],
name: json["Name"],
serialNumber: json["SerialNumber"],
created: json["Created"],
lastEdited: json["LastEdited"],
description: json["Description"] ?? "",
ownerId: json["OwnerID"],
dataId: json["DataID"],
lastKnownCoordinates: json["LastKnownCoordinates"] ?? "",
dateOfCoordinates: json["DateOfCoordinates"] ?? "",
lastDistance: json["LastDistance"] ?? "",
);
Map<String, dynamic> toJson() => {
"id": id,
"Name": name,
"SerialNumber": serialNumber,
"Created": created,
"LastEdited": lastEdited,
"Description": description,
"OwnerID": ownerId,
"DataID": dataId,
"LastKnownCoordinates": lastKnownCoordinates,
"DateOfCoordinates": dateOfCoordinates,
"LastDistance": lastDistance,
};
}
And in my controller
List<BtData> userDevices = <BtData>[];
I am searching the list like this
var getSavedDeviceFromResult = userDevices.firstWhere(
(itm) => itm.serialNumber.toString() == r.device.id.toString(),
orElse: () => null);
But i get following error.
Unhandled Exception: type '() => Null' is not a subtype of type '(() => BtData)?' of 'orElse'
How do I cope with this situation without using collection package?
Thanks
you can't return null unless you change the type of your List to :
List<BtData?> userDevices = <BtData?>[];
You can use firstOrNull
as
var getSavedDeviceFromResult = userDevices.firstOrNull(
(itm) => itm.serialNumber.toString() == r.device.id.toString());
Do not forget to import collection
import 'package:collection/collection.dart';
I am currently trying to parse this json string:
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
I created this class:
class ParseJSON {
ParseJSON({
this.imsak,
this.sunrise,
this.fajr,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.midnight,
});
String imsak;
String sunrise;
String fajr;
String dhuhr;
String asr;
String sunset;
String maghrib;
String isha;
String midnight;
factory ParseJSON.fromJson(Map<String, dynamic> json) => ParseJSON(
imsak: json["Imsak"],
sunrise: json["Sunrise"],
fajr: json["Fajr"],
dhuhr: json["Dhuhr"],
asr: json["Asr"],
sunset: json["Sunset"],
maghrib: json["Maghrib"],
isha: json["Isha"],
midnight: json["Midnight"],
);
Map<String, dynamic> toJson() => {
"Imsak": imsak,
"Sunrise": sunrise,
"Fajr": fajr,
"Dhuhr": dhuhr,
"Asr": asr,
"Sunset": sunset,
"Maghrib": maghrib,
"Isha": isha,
"Midnight": midnight,
};
}
I tried to access the contents of the json thus:
Future<List<ParseJSON>> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
ParseJSON welcomeFromJson(String str) => ParseJSON.fromJson(json.decode(str));
final welcome = welcomeFromJson(jsonResponse);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.maghrib);
print(welcome.fajr);
}
The problem is that both print(welcome.maghrib) and print(welcome.fajr) return null. Please what am i doing incorrectly? Any help would be appreciated. Thanks
Your model class is for only getting "times" object, so you need below change for parsing Json or you need to change your model class for parsing every field from Response.
Future<List<ParseJSON>?> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
var response = json.decode(jsonResponse);
ParseJSON welcome = ParseJSON.fromJson(response['results']['datetime'][0]['times']);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.maghrib);
print(welcome.fajr);
}
You can try out using this code :
import 'dart:convert';
ParseJson parseJsonFromJson(String str) => ParseJson.fromJson(json.decode(str));
String parseJsonToJson(ParseJson data) => json.encode(data.toJson());
class ParseJson {
ParseJson({
this.code,
this.status,
this.results,
});
int code;
String status;
Results results;
factory ParseJson.fromJson(Map<String, dynamic> json) => ParseJson(
code: json["code"],
status: json["status"],
results: Results.fromJson(json["results"]),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"results": results.toJson(),
};
}
class Results {
Results({
this.datetime,
this.location,
this.settings,
});
List<Datetime> datetime;
Location location;
Settings settings;
factory Results.fromJson(Map<String, dynamic> json) => Results(
datetime: List<Datetime>.from(json["datetime"].map((x) => Datetime.fromJson(x))),
location: Location.fromJson(json["location"]),
settings: Settings.fromJson(json["settings"]),
);
Map<String, dynamic> toJson() => {
"datetime": List<dynamic>.from(datetime.map((x) => x.toJson())),
"location": location.toJson(),
"settings": settings.toJson(),
};
}
class Datetime {
Datetime({
this.times,
this.date,
});
Times times;
Date date;
factory Datetime.fromJson(Map<String, dynamic> json) => Datetime(
times: Times.fromJson(json["times"]),
date: Date.fromJson(json["date"]),
);
Map<String, dynamic> toJson() => {
"times": times.toJson(),
"date": date.toJson(),
};
}
class Date {
Date({
this.timestamp,
this.gregorian,
this.hijri,
});
int timestamp;
DateTime gregorian;
DateTime hijri;
factory Date.fromJson(Map<String, dynamic> json) => Date(
timestamp: json["timestamp"],
gregorian: DateTime.parse(json["gregorian"]),
hijri: DateTime.parse(json["hijri"]),
);
Map<String, dynamic> toJson() => {
"timestamp": timestamp,
"gregorian": "${gregorian.year.toString().padLeft(4, '0')}-${gregorian.month.toString().padLeft(2, '0')}-${gregorian.day.toString().padLeft(2, '0')}",
"hijri": "${hijri.year.toString().padLeft(4, '0')}-${hijri.month.toString().padLeft(2, '0')}-${hijri.day.toString().padLeft(2, '0')}",
};
}
class Times {
Times({
this.imsak,
this.sunrise,
this.fajr,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.midnight,
});
String imsak;
String sunrise;
String fajr;
String dhuhr;
String asr;
String sunset;
String maghrib;
String isha;
String midnight;
factory Times.fromJson(Map<String, dynamic> json) => Times(
imsak: json["Imsak"],
sunrise: json["Sunrise"],
fajr: json["Fajr"],
dhuhr: json["Dhuhr"],
asr: json["Asr"],
sunset: json["Sunset"],
maghrib: json["Maghrib"],
isha: json["Isha"],
midnight: json["Midnight"],
);
Map<String, dynamic> toJson() => {
"Imsak": imsak,
"Sunrise": sunrise,
"Fajr": fajr,
"Dhuhr": dhuhr,
"Asr": asr,
"Sunset": sunset,
"Maghrib": maghrib,
"Isha": isha,
"Midnight": midnight,
};
}
class Location {
Location({
this.latitude,
this.longitude,
this.elevation,
this.city,
this.country,
this.countryCode,
this.timezone,
this.localOffset,
});
double latitude;
double longitude;
int elevation;
String city;
String country;
String countryCode;
String timezone;
int localOffset;
factory Location.fromJson(Map<String, dynamic> json) => Location(
latitude: json["latitude"].toDouble(),
longitude: json["longitude"].toDouble(),
elevation: json["elevation"],
city: json["city"],
country: json["country"],
countryCode: json["country_code"],
timezone: json["timezone"],
localOffset: json["local_offset"],
);
Map<String, dynamic> toJson() => {
"latitude": latitude,
"longitude": longitude,
"elevation": elevation,
"city": city,
"country": country,
"country_code": countryCode,
"timezone": timezone,
"local_offset": localOffset,
};
}
class Settings {
Settings({
this.timeformat,
this.school,
this.juristic,
this.highlat,
this.fajrAngle,
this.ishaAngle,
});
String timeformat;
String school;
String juristic;
String highlat;
int fajrAngle;
int ishaAngle;
factory Settings.fromJson(Map<String, dynamic> json) => Settings(
timeformat: json["timeformat"],
school: json["school"],
juristic: json["juristic"],
highlat: json["highlat"],
fajrAngle: json["fajr_angle"],
ishaAngle: json["isha_angle"],
);
Map<String, dynamic> toJson() => {
"timeformat": timeformat,
"school": school,
"juristic": juristic,
"highlat": highlat,
"fajr_angle": fajrAngle,
"isha_angle": ishaAngle,
};
}
just call this line when parse json:
final parseJson = parseJsonFromJson(jsonString);
like bellow:
Future<void> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
final welcome = jsonParseFromJson(jsonResponse);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.results.datetime[0].times.fajr);
}
I am new to working with dart/flutter!
Tell me pls how to correctly implement an abstract class in which a factory method is needed
I have a large number of models with the same methods (factory Model.fromJsom, listFromJson)! I want to make an interface for such models, but I don’t understand how to make a factory method and a static in abstract class
Examples
class Post extends Equatable {
Post({
required this.id,
required this.title,
});
final int id;
final String title;
#override
List<Object> get props => [
id,
title,
];
factory Post.fromJson(dynamic json) {
return Post(
id: json['id'] as int,
title: json['name'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
};
}
static List<Post> listFromJson(List<dynamic> json) {
return json.map((value) => Post.fromJson(value)).toList();
}
#override
String toString() {
return '''Post { id: $id, title: $title }''';
}
}
I find it's always a headache to work with JSON array directly. The solution I find is to wrap the List inside another class, in this case ListPost as follows:
class Post {
final int id;
final String title;
Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) => Post(
id: json['id'] as int,
title: json['title'] as String,
);
Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'title': title,
};
}
class ListPost {
final List<Post> list;
ListPost({required this.list});
factory ListPost.fromJson(Map<String, dynamic> json) => ListPost(
list: (json['list'] as List<dynamic>)
.map((e) => Post.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> toJson() => <String, dynamic>{
'list': list,
};
}
And the example JSON is like this:
{
"list": [
{"id": 1, "title": "TITLE_1"},
{"id": 2, "title": "TITLE_2"}
]
}
I hope this is workable for you.
You can simply use this website it will convert your json to a dart file and you can easily call the methods .fromJson and .toJson to convert from json to entity and vice versa quicktype website
JSON source
{
"greeting": "Welcome to quicktype!",
"instructions": [
"Type or paste JSON here",
"Or choose a sample above",
"quicktype will generate code in your",
"chosen language to parse the sample data"
]
}
Dart file
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
this.greeting,
this.instructions,
});
String greeting;
List<String> instructions;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
greeting: json["greeting"] == null ? null : json["greeting"],
instructions: json["instructions"] == null ? null : List<String>.from(json["instructions"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"greeting": greeting == null ? null : greeting,
"instructions": instructions == null ? null : List<dynamic>.from(instructions.map((x) => x)),
};
}
I have an application with news api from https://newsapi.org/
My model from quicktype:
// To parse this JSON data, do
//
// final news = newsFromJson(jsonString);
import 'package:meta/meta.dart';
import 'dart:convert';
List<News> newsFromJson(String str) =>
List<News>.from(json.decode(str).map((x) => News.fromJson(x)));
String newsToJson(List<News> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class News {
News({
required this.status,
required this.totalResults,
required this.articles,
});
final String status;
final int totalResults;
final List<Article> articles;
factory News.fromJson(Map<String, dynamic> json) => News(
status: json["status"],
totalResults: json["totalResults"],
articles: List<Article>.from(
json["articles"].map((x) => Article.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"totalResults": totalResults,
"articles": List<dynamic>.from(articles.map((x) => x.toJson())),
};
}
class Article {
Article({
required this.source,
required this.author,
required this.title,
required this.description,
required this.url,
required this.urlToImage,
required this.publishedAt,
required this.content,
});
final Source source;
final String author;
final String title;
final String description;
final String url;
final String urlToImage;
final DateTime publishedAt;
final String content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
source: Source.fromJson(json["source"]),
author: json["author"] == null ? null : json["author"],
title: json["title"],
description: json["description"],
url: json["url"],
urlToImage: json["urlToImage"],
publishedAt: DateTime.parse(json["publishedAt"]),
content: json["content"],
);
Map<String, dynamic> toJson() => {
"source": source.toJson(),
"author": author == null ? null : author,
"title": title,
"description": description,
"url": url,
"urlToImage": urlToImage,
"publishedAt": publishedAt.toIso8601String(),
"content": content,
};
}
class Source {
Source({
required this.id,
required this.name,
});
final String id;
final String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"] == null ? null : json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name,
};
}
In my remoteservice.dart:
import 'package:http/http.dart' as http;
import 'package:nocovid/models/news.dart';
import 'package:nocovid/utils/constant.dart';
class RemoteServices {
static var client = http.Client();
static Future<List<News>?> fetchNews() async {
final String endpoint =
'https://newsapi.org/v2/everything?q=covid19&apiKey=' + kAPIKey;
final Uri url = Uri.parse(endpoint);
final response = await client.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
return newsFromJson(jsonString);
} else {
return null;
}
}
}
newscontroller.dart
import 'package:get/state_manager.dart';
import 'package:nocovid/models/news.dart';
import 'package:nocovid/services/remote_services.dart';
class NewsController extends GetxController {
var newsList = <News>[].obs;
#override
void onInit() {
fetchNews();
super.onInit();
}
void fetchNews() async {
var news = await RemoteServices.fetchNews();
if (news != null) {
newsList.value = news;
}
}
}
And get this errors:
and
the call is performed regularly but upon showing the data, it generates these errors.
I checked some codes on github and everything seems to work, while i can't get going
Change
List<News> newsFromJson(String str) =>
List<News>.from(json.decode(str).map((x) => News.fromJson(x)));
To
News newsFromJson(String str) => News.fromJson(json.decode(str));
The Reason for this is News object is not a list, it's a complex JSON with a map that consists of a list of Articles. You need to go through API properly.
If you want a model you can use quicktype. Just paste in the URL response.
Also Change
static Future<List<News>?> fetchNews()
to
static Future<News> fetchNews()
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;
}
}