【问题标题】:Flutter how to get the data of a jsonFlutter如何获取一个json的数据
【发布时间】:2019-02-12 20:16:13
【问题描述】:

很好,我有以下问题我有一个以下 http:// 的 json,我有一个类来获取使用 https://app.quicktype.io/ 的数据,代码如下

// To parse this JSON data, do
//
//     final moviesFirstLoad = moviesFirstLoadFromJson(jsonString);

import 'dart:convert';

MoviesFirstLoad moviesFirstLoadFromJson(String str) {
  final jsonData = json.decode(str);
  return MoviesFirstLoad.fromJson(jsonData);
}

String moviesFirstLoadToJson(MoviesFirstLoad data) {
  final dyn = data.toJson();
  return json.encode(dyn);
}

class MoviesFirstLoad {
  List<Movierecent> movierecent;

  MoviesFirstLoad({
    this.movierecent,
  });

  factory MoviesFirstLoad.fromJson(Map<String, dynamic> json) => new MoviesFirstLoad(
    movierecent: new List<Movierecent>.from(json["movierecent"].map((x) => Movierecent.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "movierecent": new List<dynamic>.from(movierecent.map((x) => x.toJson())),
  };
}

class Movierecent {
  int id;
  String movieId;
  String title;
  String genre;
  String myear;
  String released;
  String runtime;
  String rated;
  String director;
  String actors;
  String plot;
  String imdbrating;
  String type;
  String production;
  int internalid;
  String poster;

  Movierecent({
    this.id,
    this.movieId,
    this.title,
    this.genre,
    this.myear,
    this.released,
    this.runtime,
    this.rated,
    this.director,
    this.actors,
    this.plot,
    this.imdbrating,
    this.type,
    this.production,
    this.internalid,
    this.poster,
  });

  factory Movierecent.fromJson(Map<String, dynamic> json) => new Movierecent(
    id: json["id"],
    movieId: json["movieID"],
    title: json["title"],
    genre: json["genre"],
    myear: json["myear"],
    released: json["released"],
    runtime: json["runtime"],
    rated: json["rated"],
    director: json["director"],
    actors: json["actors"],
    plot: json["plot"],
    imdbrating: json["imdbrating"],
    type: json["type"],
    production: json["production"],
    internalid: json["internalid"],
    poster: json["poster"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "movieID": movieId,
    "title": title,
    "genre": genre,
    "myear": myear,
    "released": released,
    "runtime": runtime,
    "rated": rated,
    "director": director,
    "actors": actors,
    "plot": plot,
    "imdbrating": imdbrating,
    "type": type,
    "production": production,
    "internalid": internalid,
    "poster": poster,
  };
}

现在第一个标签显示我应该使用

final moviesFirstLoad = moviesFirstLoadFromJson(jsonString);

因此我有以下内容,在这里我不知道该怎么做,因为访问数据以将它们放在列表中就像

Future<List<Movierecent>> loadMovies() async {

final response = await http.get("http://emovies.evolucionone.com/");
 if (response.statusCode == 200){
  final moviesFirstLoad = moviesFirstLoadFromJson(response.body);
  return moviesFirstLoad.movierecent;
 }else{
  throw Exception ('Failed to load Data');
 }
}

如果有人帮助我,我需要帮助来获取 json 的数据我已经阅读了几个主题,但它们都不适合我...

【问题讨论】:

  • moviesFirstLoad 的类型为 MoviesFirstLoadmoviesFirstLoad.movierecent 应该给你电影列表(Movierecent 类型)。所以只需将 return moviesFirstLoad.movierecent; 添加到 if 块中。
  • 不工作错误说返回类型 'List' 不是方法 'loadMovies' 定义的'Future>'。
  • 您可能想要添加响应,例如错误是什么。
  • return moviesFirstLoad.movierecent; 这告诉我这个错误The return type 'List&lt;Movierecent&gt;' isn't a 'Future&lt;List&lt;MoviesFirstLoad&gt;&gt;', as defined by the method 'loadMovies' 以及我如何在列表中得到结果
  • 如果您需要获取电影列表,请将返回类型更改为Future&lt;List&lt;Movierecent&gt;&gt;,或者如果您想要完整的对象将其更改为Future&lt;MoviesFirstLoad&gt;并返回moviesFirstLoad

标签: json dart flutter


【解决方案1】:

我自己回答我的问题

这是从json中获取数据


Future<MoviesFirstLoad> loadMovies() async {
  final Response response = await http.get(dogApiUrl);
  //final List<Movierecent> posterimage = List<Movierecent>();
  if (response.statusCode == 200){
    //final responsejson = json.decode(response.body);
    final moviesFirstLoad = moviesFirstLoadFromJson(response.body);
    // moviesFirstLoad.movierecent.forEach((poster) => posterimage.add(poster));
    print(moviesFirstLoad);
    return moviesFirstLoad;
  }else{
    throw Exception ('Failed to load Data');
  }
}

在列表中显示数据

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Movies')),
      body: FutureBuilder(
        future: loadMovies(),
        builder: (BuildContext context, AsyncSnapshot<AppData> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: snapshot.data.movierecent.length,
            itemBuilder: (BuildContext context, int index) {
              final Movierecent movie = snapshot.data.movierecent[index];
              return ListTile(
                title: Text(movie.title),
                subtitle: Text(movie.genre),
              );
            },
          );
        },
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    loadMovies() 返回Future&lt;List&lt;Movierecent&gt;&gt;,这是一个未来。如果你想要电影的基础列表,你可以做一些像

    loadMovies().then((List<Movierecent> movieList) {
     /* do what you want to do here like invoking setState()....*/
    }.catchError((e) {
    /* Handle Error scenario here */
    };
    

    您可能想推荐Dart documentation of Futures

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2019-10-16
      • 2021-12-24
      • 1970-01-01
      • 2021-12-24
      • 2021-07-14
      相关资源
      最近更新 更多