首页 > 解决方案 > 使用 Flutter 从 API 接收数据

问题描述

我使用颤振的时间不长,我不知道如何像下面描述的那样检索数据。

我用 API 创建了一个应用程序。我收到了除画廊图像、程序、附加信息之外的所有数据。

谁能向我解释如何从 API 中检索图库图像、程序和附加信息?

如果您可以编写我可以使用的代码片段。谢谢。

'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;
  }
}

标签: flutterdarthybrid-mobile-app

解决方案


您可以从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;
  }
}

推荐阅读