将json数据映射到dart类,然后放入flutter listview

时间:2019-06-18 13:09:19

标签: json api flutter

这是我第一次使用api,但是我收到的json很大且很复杂,因此情况如下:

  1. 我有一个从api检索的json数据
  2. json中的数据必须在flutter的列表视图中显示
  3. 我创建了一个类来映射数据:
class Anime {
  int malId;
  String url;
  String title;
  String imageUrl;
  String synopsis;
  String type;
  String airingStart;
  Null episodes;
  int members;
  List<Genres> genres;
  String source;
  List<Producers> producers;
  double score;
  List<String> licensors;
  bool r18;
  bool kids;
  bool continuing;

  Anime(
      this.malId,
      this.url,
      this.title,
      this.imageUrl,
      this.synopsis,
      this.type,
      this.airingStart,
      this.episodes,
      this.members,
      this.genres,
      this.source,
      this.producers,
      this.score,
      this.licensors,
      this.r18,
      this.kids,
      this.continuing);

  Anime.fromJson(Map<String, dynamic> json) {
    malId = json['mal_id'];
    url = json['url'];
    title = json['title'];
    imageUrl = json['image_url'];
    synopsis = json['synopsis'];
    type = json['type'];
    airingStart = json['airing_start'];
    episodes = json['episodes'];
    members = json['members'];
    if (json['genres'] != null) {
      genres = new List<Genres>();
      json['genres'].forEach((v) {
        genres.add(new Genres.fromJson(v));
      });
    }
    source = json['source'];
    if (json['producers'] != null) {
      producers = new List<Producers>();
      json['producers'].forEach((v) {
        producers.add(new Producers.fromJson(v));
      });
    }
    score = json['score'];
    licensors = json['licensors'].cast<String>();
    r18 = json['r18'];
    kids = json['kids'];
    continuing = json['continuing'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['mal_id'] = this.malId;
    data['url'] = this.url;
    data['title'] = this.title;
    data['image_url'] = this.imageUrl;
    data['synopsis'] = this.synopsis;
    data['type'] = this.type;
    data['airing_start'] = this.airingStart;
    data['episodes'] = this.episodes;
    data['members'] = this.members;
    if (this.genres != null) {
      data['genres'] = this.genres.map((v) => v.toJson()).toList();
    }
    data['source'] = this.source;
    if (this.producers != null) {
      data['producers'] = this.producers.map((v) => v.toJson()).toList();
    }
    data['score'] = this.score;
    data['licensors'] = this.licensors;
    data['r18'] = this.r18;
    data['kids'] = this.kids;
    data['continuing'] = this.continuing;
    return data;
  }
}
  1. 这是我用来获取json数据的函数:
Future getdata(String season,int year) async {
    var url = baseUrl + '/season/$year/${season.toString()}';
    print('hitting url $url');
    var response = await http.get(url);
    var jsondata= jsonDecode(response.body);
  }
}
  1. 我想要的是修改getdata函数,以使其将json映射到我创建的类中,然后使用futrebuilder将其显示在列表视图中。

1 个答案:

答案 0 :(得分:0)

没有我看到您的json数据并确保您的模型类匹配的情况,我假设您应该能够执行以下操作

 import 'package:jikan_dart/src/model/season/anime.dart' as ac; //to avoid package conflict use 'as' then you can refer to this package using what ever keyword you've picked

List<ac.Anime> animeList = new List<ac.Anime>();
for(var item in jsonData){
    ac.Anime anime = ac.Anime.fromJson(item);
    animeList.add(item);
}

理想情况下,您现在将列表保存在sqflite database中。 (除非您希望用户始终进行api调用)。

然后,在您的视图类中,您可以创建一个futurebuilder,该futurebuilder调用数据库以检索数据并将其显示在列表视图中。

_animeList(String season, int year){
   new Container(
    child: new FutureBuilder<List<ac.Anime>>(
              future: getdata(season, year),
                builder: (BuildContext context, AsyncSnapshot<List<ac.Anime>> snapshot) {
                  if(!snapshot.hasData){
                      return new Center(
                        child: new CircularProgressIndicator(),
                      );
                     }else{
                   return new ListView.builder(
                      scrollDirection: Axis.vertical,
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, int index) {
                         return Container(
                                    child: Text('${snapshot.data.title}'),
                      ); //return whatever widget you want to use to display your data
                    }
                  }
}