【问题标题】:Map json data into dart class then put into flutter listview将 json 数据映射到 dart 类中,然后放入 flutter listview
【发布时间】:2019-11-01 03:31:11
【问题描述】:

我是第一次使用api,但是我收到的json很大很复杂,所以场景如下:

  1. 我有一个从 api 检索到的 json 数据
  2. json中的数据在flutter中必须以listview的形式展示
  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 将其显示在列表视图中。

【问题讨论】:

    标签: json api flutter


    【解决方案1】:

    如果我没有看到您的 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。

    _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
                        }
                      }
    }
    

    【讨论】:

    • 我遇到了这个错误:名称“Anime”是在库“package:anime_app/Anime/anime_classes.dart”和“package:jikan_dart/src/model/season/anime.dart”中定义的'。尝试对其中一个导入指令使用“作为前缀”,或者对所有 import 指令隐藏名称。dart(ambiguous_import)
    • 再次更新了答案,因为我引用了错误的包。每当您想引用动画模型时,您都必须使用“ac.Anime”或您选择的任何前缀,这将告诉 IDE 在您的代码中引用时应该使用哪个类。
    • 你用 list 来表示什么是 Drug?
    • 对我没用,你能给我一个完整的代码来实现jikan api到flutter listview
    • 这是一个错字,我复制了我在应用程序中使用的代码,应该是 list。我不知道 jkan api 是什么
    猜你喜欢
    • 2022-01-16
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2018-05-11
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多