简体   繁体   中英

How to get data from url that is in response JSON - Flutter

I am using GET to https://rickandmortyapi.com/api/character/ in JSON. That JSON contains an array of links of episode , like https://rickandmortyapi.com/api/episode/4 . How can I GET episode name like S01E04 from episode link? My code now is:

character.class

import 'dart:convert';
import 'package:rick_and_morty_characters/services/webservice.dart';
import 'package:rick_and_morty_characters/utils/constants.dart';

class Character {
  final int id;
  final String name;
  final String status;
  final String image;
  final Episode episode;
  Character({this.id, this.name, this.status, this.image, this.episode});
  factory Character.fromJson(Map<String,dynamic> json) {
    return Character(
      id: json['id'],
      name: json['name'],
      status: json['status'],
      image: json['image'] ?? Constants.DEFAULT_AVATAR,
      episode: Episode.fromJson(json['episode'])
    );
  }

  static Resource<List<Character>> get all {
    return Resource(
        url: Constants.R_A_M_CHARACTERS,
        parse: (response) {
          final result = json.decode(response.body);
          Iterable list = result['results'];
          return list.map((model) => Character.fromJson(model)).toList();
        }
    );
  }
}

class Episode {
  final String episodeLink;
  Episode({this.episodeLink});
  factory Episode.fromJson(Map<String,dynamic> json) {
    return Episode(
      episodeLink: json['episode']
    );
  }
}

constants.dart

class Constants {
  static final String R_A_M_CHARACTERS = 'https://rickandmortyapi.com/api/character/';
  static final String DEFAULT_AVATAR = 'https://rickandmortyapi.com/api/character/avatar/1.jpeg';
}

webservice.dart

import 'package:http/http.dart' as http;
import 'package:http/http.dart';

class Resource<T> {
  final String url;
  T Function(Response response) parse;
  Resource({this.url,this.parse});
}

class Webservice {
  Future<T> load<T>(Resource<T> resource) async {
    final response = await http.get(resource.url);
    if(response.statusCode == 200) {
      return resource.parse(response);
    } else {
      throw Exception('Failed to load data!');
    }
  }
}

try pasting an example of your JSON here

  https://app.quicktype.io/

the build an object and copy paste the dart code.

Then, when you get a response from your api, just parse your JSON to the newly created object.

And the just use the object as you wish to get the info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM