繁体   English   中英

无效参数(输入):不得为 null - Flutter

[英]Invalid argument(s) (input): Must not be null - Flutter

我正在构建一个电影应用程序,其中我使用 TMDB 使用无限滚动分页 3.0.1+1 库加载了海报列表。 第一组数据加载良好,但在滚动后和加载第二组数据之前,我得到以下异常。

"Invalid argument(s) (input): Must not be null"

虽然手动调试我发现异常发生在results = Movie.fromJson(jsonMap).results; services.dart (电影 model 文件)中。 任何帮助,将不胜感激。

movie_page.dart

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:zlikx/services.dart';

import 'movies.dart';

class MoviesPage extends StatefulWidget {
  @override
  State<MoviesPage> createState() => _MoviesPageState();
}

class _MoviesPageState extends State<MoviesPage> {
  static const _pageSize = 20;
  final PagingController<int, Result> _pagingController = PagingController(firstPageKey: 1);

  @override
  void initState() {
    print('insideinit');
    _pagingController.addPageRequestListener((pageKey) {
      _fetchPage(pageKey);
    });
    super.initState();
  }

  Future<void> _fetchPage(int pageKey) async {
    try {
      final newItems = await Services().fetchmovies(pageKey);
      print('newItems.length' + newItems.length.toString());
      final isLastPage = newItems.length < _pageSize;
      if (isLastPage) {
        print('inside is last page');
        _pagingController.appendLastPage(newItems);
      } else {
        print('pageKey' + pageKey.toString());
        final nextPageKey = pageKey + 1;
        print('nextPageKey :' + nextPageKey.toString());
        _pagingController.appendPage(newItems, nextPageKey);
      }
    } catch (error) {
      _pagingController.error = error;
      print('Paging Error: ' + error.toString());
    }
  }

  @override
  Widget build(BuildContext context) => RefreshIndicator(
        onRefresh: () => Future.sync(
          () => _pagingController.refresh(),
        ),
        child: PagedGridView(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1 / 1.5),
          pagingController: _pagingController,
          builderDelegate: PagedChildBuilderDelegate<Result>(
            itemBuilder: (context, result, index) {
              return Image.network(
                'https://image.tmdb.org/t/p/w500' + result.posterPath,
                fit: BoxFit.fill,
              );
            },
          ),
          padding: const EdgeInsets.all(16),
        ),
      );

  @override
  void dispose() {
    _pagingController.dispose();
    super.dispose();
  }
}


services.dart

import 'dart:convert';

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

class Services {
  static const String movie_url = "https://api.themoviedb.org/3/movie/popular?api_key=[KEY_HIDDEN]&language=en-US&page=1";
  static const String popular_movies = "https://api.themoviedb.org/3/movie/popular?api_key=[KEY_HIDDEN]b&language=en-US&page=";

  Future<Movie> getMovies() async {
    var client = http.Client();
    var moviesModel;

    try {
      var response = await client.get(Uri.parse(movie_url));
      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = json.decode(jsonString);

        moviesModel = Movie.fromJson(jsonMap);
      }
      // ignore: non_constant_identifier_names
    } catch (Exception) {
      print(Exception.toString());
      return moviesModel;
    }

    return moviesModel;
  }

  Future<List<Result>> fetchmovies(int pageKey) async {
    var client = http.Client();
    var results;
    print('Inside fetchmovies');
    try {
      print('pageKey: ' + pageKey.toString());
      var urlToHit = Uri.parse(popular_movies + pageKey.toString());
      print(urlToHit);
      var response = await client.get(urlToHit);
      print('response.body: ' + response.body.toString());
      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = json.decode(jsonString);
        print('jsonMap: ' + jsonMap.toString());
        results = Movie.fromJson(jsonMap).results;
        print('results' + results.toString());
      } else {
        print('response.statusCode: ' + response.statusCode.toString());
      }
      // ignore: non_constant_identifier_names
    } catch (Exception) {
      print('fetch movies Exception ' + Exception.toString());
      return results;
    }

    return results;
  }
}

我的 model class 电影。dart

// To parse this JSON data, do
//
//     final movie = movieFromJson(jsonString);

import 'dart:convert';

Movie movieFromJson(String str) => Movie.fromJson(json.decode(str));

String movieToJson(Movie data) => json.encode(data.toJson());

class Movie {
    Movie({
        this.page,
        this.results,
        this.totalPages,
        this.totalResults,
    });

    int page;
    List<Result> results;
    int totalPages;
    int totalResults;

    factory Movie.fromJson(Map<String, dynamic> json) => Movie(
        page: json["page"],
        results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
        totalPages: json["total_pages"],
        totalResults: json["total_results"],
    );

    Map<String, dynamic> toJson() => {
        "page": page,
        "results": List<dynamic>.from(results.map((x) => x.toJson())),
        "total_pages": totalPages,
        "total_results": totalResults,
    };
}

class Result {
    Result({
        this.adult,
        this.backdropPath,
        this.genreIds,
        this.id,
        this.originalLanguage,
        this.originalTitle,
        this.overview,
        this.popularity,
        this.posterPath,
        this.releaseDate,
        this.title,
        this.video,
        this.voteAverage,
        this.voteCount,
    });

    bool adult;
    String backdropPath;
    List<int> genreIds;
    int id;
    String originalLanguage;
    String originalTitle;
    String overview;
    double popularity;
    String posterPath;
    DateTime releaseDate;
    String title;
    bool video;
    double voteAverage;
    int voteCount;

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        adult: json["adult"],
        backdropPath: json["backdrop_path"],
        genreIds: List<int>.from(json["genre_ids"].map((x) => x)),
        id: json["id"],
        originalLanguage: json["original_language"],
        originalTitle: json["original_title"],
        overview: json["overview"],
        popularity: json["popularity"].toDouble(),
        posterPath: json["poster_path"],
        releaseDate: DateTime.parse(json["release_date"]),
        title: json["title"],
        video: json["video"],
        voteAverage: json["vote_average"].toDouble(),
        voteCount: json["vote_count"],
    );

    Map<String, dynamic> toJson() => {
        "adult": adult,
        "backdrop_path": backdropPath,
        "genre_ids": List<dynamic>.from(genreIds.map((x) => x)),
        "id": id,
        "original_language": originalLanguage,
        "original_title": originalTitle,
        "overview": overview,
        "popularity": popularity,
        "poster_path": posterPath,
        "release_date": "${releaseDate.year.toString().padLeft(4, '0')}-${releaseDate.month.toString().padLeft(2, '0')}-${releaseDate.day.toString().padLeft(2, '0')}",
        "title": title,
        "video": video,
        "vote_average": voteAverage,
        "vote_count": voteCount,
    };
}

控制台 output

I/flutter (14202): pageKey: 2
I/flutter (14202): https://api.themoviedb.org/3/movie/popular?api_key=9b31264aec7cd32ff6ff94ebceecb01b&language=en-US&page=2
I/flutter (14202): response.body: {"page":2,"results":[{"adult":false,"backdrop_path":"/70AV2Xx5FQYj20labp0EGdbjI6E.jpg","genre_ids":[28,80],"id":637649,"original_language":"en","original_title":"Wrath of Man","overview":"A cold and mysterious new security guard for a Los Angeles cash truck company surprises his co-workers when he unleashes precision skills during a heist. The crew is left wondering who he is and where he came from. Soon, the marksman's ultimate motive becomes clear as he takes dramatic and irrevocable steps to settle a score.","popularity":642.634,"poster_path":"/YxopfHpsCV1oF8CZaL4M3Eodqa.jpg","release_date":"2021-04-22","title":"Wrath of Man","video":false,"vote_average":8,"vote_count":308},{"adult":false,"backdrop_path":"/7HtvmsLrDeiAgDGa1W3m6senpfE.jpg","genre_ids":[12,16,10751],"id":681260,"original_language":"en","original_title":"Maya the Bee: The Golden Orb","overview":"When Maya, a headstrong little bee, and her best friend Willi, rescue an ant princess they find themselves in the middle of an epic b
I/flutter (14202): jsonMap: {page: 2, results: [{adult: false, backdrop_path: /70AV2Xx5FQYj20labp0EGdbjI6E.jpg, genre_ids: [28, 80], id: 637649, original_language: en, original_title: Wrath of Man, overview: A cold and mysterious new security guard for a Los Angeles cash truck company surprises his co-workers when he unleashes precision skills during a heist. The crew is left wondering who he is and where he came from. Soon, the marksman's ultimate motive becomes clear as he takes dramatic and irrevocable steps to settle a score., popularity: 642.634, poster_path: /YxopfHpsCV1oF8CZaL4M3Eodqa.jpg, release_date: 2021-04-22, title: Wrath of Man, video: false, vote_average: 8, vote_count: 308}, {adult: false, backdrop_path: /7HtvmsLrDeiAgDGa1W3m6senpfE.jpg, genre_ids: [12, 16, 10751], id: 681260, original_language: en, original_title: Maya the Bee: The Golden Orb, overview: When Maya, a headstrong little bee, and her best friend Willi, rescue an ant princess they find themselves in the middle of an epic bug battle that will take t
I/flutter (14202): fetch movies Exception Invalid argument(s) (input): Must not be null
I/flutter (14202): Paging Error: NoSuchMethodError: The getter 'length' was called on null.
I/flutter (14202): Receiver: null
I/flutter (14202): Tried calling: length
D/ViewRootImpl[MainActivity](14202): windowFocusChanged hasFocus=false inTouchMode=true

响应样本

{
  "page": 2,
  "results": [
    {
      "adult": false,
      "backdrop_path": "/z2UtGA1WggESspi6KOXeo66lvLx.jpg",
      "genre_ids": [
        18,
        878,
        53
      ],
      "id": 520763,
      "original_language": "en",
      "original_title": "A Quiet Place Part II",
      "overview": "Following the events at home, the Abbott family now face the terrors of the outside world. Forced to venture into the unknown, they realize that the creatures that hunt by sound are not the only threats that lurk beyond the sand path.",
      "popularity": 690.813,
      "poster_path": "/4q2hz2m8hubgvijz8Ez0T2Os2Yv.jpg",
      "release_date": "2021-05-21",
      "title": "A Quiet Place Part II",
      "video": false,
      "vote_average": 7.5,
      "vote_count": 58
    },
    {
      "adult": false,
      "backdrop_path": "/70AV2Xx5FQYj20labp0EGdbjI6E.jpg",
      "genre_ids": [
        28,
        80
      ],
      "id": 637649,
      "original_language": "en",
      "original_title": "Wrath of Man",
      "overview": "A cold and mysterious new security guard for a Los Angeles cash truck company surprises his co-workers when he unleashes precision skills during a heist. The crew is left wondering who he is and where he came from. Soon, the marksman's ultimate motive becomes clear as he takes dramatic and irrevocable steps to settle a score.",
      "popularity": 899.688,
      "poster_path": "/YxopfHpsCV1oF8CZaL4M3Eodqa.jpg",
      "release_date": "2021-04-22",
      "title": "Wrath of Man",
      "video": false,
      "vote_average": 8,
      "vote_count": 367
    },
    {
      "adult": false,
      "backdrop_path": "/7HtvmsLrDeiAgDGa1W3m6senpfE.jpg",
      "genre_ids": [
        12,
        16,
        10751
      ],
      "id": 681260,
      "original_language": "en",
      "original_title": "Maya the Bee: The Golden Orb",
      "overview": "When Maya, a headstrong little bee, and her best friend Willi, rescue an ant princess they find themselves in the middle of an epic bug battle that will take them to strange new worlds and test their friendship to its limits.",
      "popularity": 890.077,
      "poster_path": "/tMS2qcbhbkFpcwLnbUE9o9IK4HH.jpg",
      "release_date": "2021-01-07",
      "title": "Maya the Bee: The Golden Orb",
      "video": false,
      "vote_average": 6.6,
      "vote_count": 32
    },
    {
      "adult": false,
      "backdrop_path": "/5Zv5KmgZzdIvXz2KC3n0MyecSNL.jpg",
      "genre_ids": [
        28,
        53,
        80
      ],
      "id": 634528,
      "original_language": "en",
      "original_title": "The Marksman",
      "overview": "Jim Hanson’s quiet life is suddenly disturbed by two people crossing the US/Mexico border – a woman and her young son – desperate to flee a Mexican cartel. After a shootout leaves the mother dead, Jim becomes the boy’s reluctant defender. He embraces his role as Miguel’s protector and will stop at nothing to get him to safety, as they go on the run from the relentless assassins.",
      "popularity": 739.328,
      "poster_path": "/6vcDalR50RWa309vBH1NLmG2rjQ.jpg",
      "release_date": "2021-01-15",
      "title": "The Marksman",
      "video": false,
      "vote_average": 7.4,
      "vote_count": 505
    },
    {
      "adult": false,
      "backdrop_path": "/jFINtstDUh0vHOGImpMAmLrPcXy.jpg",
      "genre_ids": [
        28,
        27,
        35
      ],
      "id": 643586,
      "original_language": "en",
      "original_title": "Willy's Wonderland",
      "overview": "When his car breaks down, a quiet loner agrees to clean an abandoned family fun center in exchange for repairs. He soon finds himself waging war against possessed animatronic mascots while trapped inside Willy's Wonderland.",
      "popularity": 700.784,
      "poster_path": "/keEnkeAvifw8NSEC4f6WsqeLJgF.jpg",
      "release_date": "2021-02-12",
      "title": "Willy's Wonderland",
      "video": false,
      "vote_average": 6.7,
      "vote_count": 227
    },
    {
      "adult": false,
      "backdrop_path": "/sPeqIdCYvcmeZe5fCu7JgMnf1HL.jpg",
      "genre_ids": [
        16,
        35,
        878
      ],
      "id": 825597,
      "original_language": "en",
      "original_title": "Maggie Simpson in The Force Awakens from Its Nap",
      "overview": "In a daycare far, far away… but still in Springfield, Maggie is on an epic quest for her stolen pacifier. Her adventure brings her face-to-face with young Padawans, Sith Lords, familiar droids, Rebel scum, and an ultimate battle against the dark side, in this original short celebrating the Star Wars galaxy.",
      "popularity": 792.587,
      "poster_path": "/2xnf2ZaGXudvgBKPtVXMkNeooh1.jpg",
      "release_date": "2021-05-04",
      "title": "Maggie Simpson in The Force Awakens from Its Nap",
      "video": false,
      "vote_average": 6.8,
      "vote_count": 49
    },
    {
      "adult": false,
      "backdrop_path": "/xXHZeb1yhJvnSHPzZDqee0zfMb6.jpg",
      "genre_ids": [
        28,
        53,
        80
      ],
      "id": 385128,
      "original_language": "en",
      "original_title": "F9",
      "overview": "Dominic Toretto and his crew join forces to battle the most skilled assassin and high-performance driver they've ever encountered: his forsaken brother.",
      "popularity": 511.888,
      "poster_path": "/bOFaAXmWWXC3Rbv4u4uM9ZSzRXP.jpg",
      "release_date": "2021-05-19",
      "title": "F9",
      "video": false,
      "vote_average": 8.3,
      "vote_count": 66
    },
    {
      "adult": false,
      "backdrop_path": "/czHYg6LQ5926OL8wj5kC09pNR12.jpg",
      "genre_ids": [
        27,
        35
      ],
      "id": 647302,
      "original_language": "en",
      "original_title": "Benny Loves You",
      "overview": "Jack, a man desperate to improve his life throws away his beloved childhood plush, Benny. It’s a move that has disastrous consequences when Benny springs to life with deadly intentions!",
      "popularity": 708.777,
      "poster_path": "/mQ8vALvqA0z0qglG3gI6xpVcslo.jpg",
      "release_date": "2019-11-21",
      "title": "Benny Loves You",
      "video": false,
      "vote_average": 6,
      "vote_count": 29
    },
    {
      "adult": false,
      "backdrop_path": "/z8TvnEVRenMSTemxYZwLGqFofgF.jpg",
      "genre_ids": [
        14,
        28,
        12
      ],
      "id": 458576,
      "original_language": "en",
      "original_title": "Monster Hunter",
      "overview": "A portal transports Cpt. Artemis and an elite unit of soldiers to a strange world where powerful monsters rule with deadly ferocity. Faced with relentless danger, the team encounters a mysterious hunter who may be their only hope to find a way home.",
      "popularity": 614.349,
      "poster_path": "/1UCOF11QCw8kcqvce8LKOO6pimh.jpg",
      "release_date": "2020-12-03",
      "title": "Monster Hunter",
      "video": false,
      "vote_average": 7.1,
      "vote_count": 1672
    },
    {
      "adult": false,
      "backdrop_path": "/9ns9463dwOeo1CK1JU2wirL5Yi1.jpg",
      "genre_ids": [
        35,
        10751,
        16
      ],
      "id": 587807,
      "original_language": "en",
      "original_title": "Tom & Jerry",
      "overview": "Tom the cat and Jerry the mouse get kicked out of their home and relocate to a fancy New York hotel, where a scrappy employee named Kayla will lose her job if she can’t evict Jerry before a high-class wedding at the hotel. Her solution? Hiring Tom to get rid of the pesky mouse.",
      "popularity": 578.077,
      "poster_path": "/8XZI9QZ7Pm3fVkigWJPbrXCMzjq.jpg",
      "release_date": "2021-02-11",
      "title": "Tom & Jerry",
      "video": false,
      "vote_average": 7.3,
      "vote_count": 1404
    },
    {
      "adult": false,
      "backdrop_path": "/ovggmAOu1IbPGTQE8lg4lBasNC7.jpg",
      "genre_ids": [
        878,
        28,
        12,
        53
      ],
      "id": 412656,
      "original_language": "en",
      "original_title": "Chaos Walking",
      "overview": "Two unlikely companions embark on a perilous adventure through the badlands of an unexplored planet as they try to escape a dangerous and disorienting reality, where all inner thoughts are seen and heard by everyone.",
      "popularity": 571.196,
      "poster_path": "/9kg73Mg8WJKlB9Y2SAJzeDKAnuB.jpg",
      "release_date": "2021-02-24",
      "title": "Chaos Walking",
      "video": false,
      "vote_average": 7.1,
      "vote_count": 646
    },
    {
      "adult": false,
      "backdrop_path": "/srYya1ZlI97Au4jUYAktDe3avyA.jpg",
      "genre_ids": [
        14,
        28,
        12
      ],
      "id": 464052,
      "original_language": "en",
      "original_title": "Wonder Woman 1984",
      "overview": "A botched store robbery places Wonder Woman in a global battle against a powerful and mysterious ancient force that puts her powers in jeopardy.",
      "popularity": 550.027,
      "poster_path": "/8UlWHLMpgZm9bx6QYh0NFoq67TZ.jpg",
      "release_date": "2020-12-16",
      "title": "Wonder Woman 1984",
      "video": false,
      "vote_average": 6.7,
      "vote_count": 5196
    },
    {
      "adult": false,
      "backdrop_path": "/h9DIlghaiTxbQbt1FIwKNbQvEL.jpg",
      "genre_ids": [
        28,
        12,
        53
      ],
      "id": 581387,
      "original_language": "ko",
      "original_title": "백두산",
      "overview": "A group of unlikely heroes from across the Korean peninsula try to save the day after a volcano erupts on the mythical and majestic Baekdu Mountain.",
      "popularity": 517.126,
      "poster_path": "/zoeKREZ2IdAUnXISYCS0E6H5BVh.jpg",
      "release_date": "2019-12-19",
      "title": "Ashfall",
      "video": false,
      "vote_average": 6.4,
      "vote_count": 266
    },
    {
      "adult": false,
      "backdrop_path": "/z7HLq35df6ZpRxdMAE0qE3Ge4SJ.jpg",
      "genre_ids": [
        28,
        12,
        35
      ],
      "id": 615678,
      "original_language": "en",
      "original_title": "Thunder Force",
      "overview": "In a world where supervillains are commonplace, two estranged childhood best friends reunite after one devises a treatment that gives them powers to protect their city.",
      "popularity": 531.611,
      "poster_path": "/3mKMWP5OokB7QpcOMA1yl8BXFAF.jpg",
      "release_date": "2021-04-09",
      "title": "Thunder Force",
      "video": false,
      "vote_average": 5.8,
      "vote_count": 607
    },
    {
      "adult": false,
      "backdrop_path": "/y0SiXoTLQp93NbLQ4XhgVz18UAS.jpg",
      "genre_ids": [
        16,
        28,
        14
      ],
      "id": 663558,
      "original_language": "zh",
      "original_title": "新神榜:哪吒重生",
      "overview": "3000 years after the boy-god Nezha conquers the Dragon King then disappears in mythological times, he returns as an ordinary man to find his own path to becoming a true hero.",
      "popularity": 567.388,
      "poster_path": "/6goDkAD6J3br81YMQf0Gat8Bqjy.jpg",
      "release_date": "2021-02-06",
      "title": "New Gods: Nezha Reborn",
      "video": false,
      "vote_average": 8.6,
      "vote_count": 165
    },
    {
      "adult": false,
      "backdrop_path": "/fRrpOILyXuWaWLmqF7kXeMVwITQ.jpg",
      "genre_ids": [
        27,
        53,
        12,
        9648
      ],
      "id": 522444,
      "original_language": "en",
      "original_title": "Black Water: Abyss",
      "overview": "An adventure-loving couple convince their friends to explore a remote, uncharted cave system in the forests of Northern Australia. With a tropical storm approaching, they abseil into the mouth of the cave, but when the caves start to flood, tensions rise as oxygen levels fall and the friends find themselves trapped. Unknown to them, the storm has also brought in a pack of dangerous and hungry crocodiles.",
      "popularity": 511.564,
      "poster_path": "/95S6PinQIvVe4uJAd82a2iGZ0rA.jpg",
      "release_date": "2020-07-09",
      "title": "Black Water: Abyss",
      "video": false,
      "vote_average": 5.1,
      "vote_count": 217
    },
    {
      "adult": false,
      "backdrop_path": null,
      "genre_ids": [
        28,
        53
      ],
      "id": 385687,
      "original_language": "en",
      "original_title": "Fast & Furious 10",
      "overview": "The tenth and penultimate installment of the Fast and Furious franchise.",
      "popularity": 469.311,
      "poster_path": "/2DyEk84XnbJEdPlGF43crxfdtHH.jpg",
      "title": "Fast & Furious 10",
      "video": false,
      "vote_average": 0,
      "vote_count": 0
    },
    {
      "adult": false,
      "backdrop_path": "/mi76WsBDStlmU1taHXasYh10LEm.jpg",
      "genre_ids": [
        35,
        18
      ],
      "id": 676842,
      "original_language": "es",
      "original_title": "Después de ti",
      "overview": "Su, a woman whose friends are only men, finds herself forced to follow a series of absurd instructions to overcome the unexpected death of her fiancé.",
      "popularity": 577.181,
      "poster_path": "/vX1XLbrHxpryX9EOWI3akbasz6c.jpg",
      "release_date": "2021-04-08",
      "title": "Instructions for Su",
      "video": false,
      "vote_average": 7.8,
      "vote_count": 45
    },
    {
      "adult": false,
      "backdrop_path": "/kf456ZqeC45XTvo6W9pW5clYKfQ.jpg",
      "genre_ids": [
        10751,
        16,
        35,
        18,
        10402,
        14
      ],
      "id": 508442,
      "original_language": "en",
      "original_title": "Soul",
      "overview": "Joe Gardner is a middle school teacher with a love for jazz music. After a successful gig at the Half Note Club, he suddenly gets into an accident that separates his soul from his body and is transported to the You Seminar, a center in which souls develop and gain passions before being transported to a newborn child. Joe must enlist help from the other souls-in-training, like 22, a soul who has spent eons in the You Seminar, in order to get back to Earth.",
      "popularity": 503.845,
      "poster_path": "/hm58Jw4Lw8OIeECIq5qyPYhAeRJ.jpg",
      "release_date": "2020-12-25",
      "title": "Soul",
      "video": false,
      "vote_average": 8.3,
      "vote_count": 6110
    },
    {
      "adult": false,
      "backdrop_path": "/aMFl4wOPhJ7NVua6SgU9zIJvFSx.jpg",
      "genre_ids": [
        16,
        10751,
        35,
        12,
        10770
      ],
      "id": 755812,
      "original_language": "fr",
      "original_title": "Miraculous World : New York, les héros unis",
      "overview": "During a school field trip, Ladybug and Cat Noir meet the American superheroes, whom they have to save from an akumatised super-villain. They discover that Miraculous exist in the United States too.",
      "popularity": 469.299,
      "poster_path": "/19kfvGktytDZInUmpv3WlaHoTxP.jpg",
      "release_date": "2020-09-26",
      "title": "Miraculous World: New York, United HeroeZ",
      "video": false,
      "vote_average": 8.3,
      "vote_count": 707
    }
  ],
  "total_pages": 500,
  "total_results": 10000
}

更新 Model

// To parse this JSON data, do
//
//     final movie = movieFromJson(jsonString);

import 'dart:convert';

Movie movieFromJson(String str) => Movie.fromJson(json.decode(str));

String movieToJson(Movie data) => json.encode(data.toJson());

class Movie {
  Movie({
    required this.page,
    required this.results,
    required this.totalPages,
    required this.totalResults,
  });

  int page;
  List<Result> results;
  int totalPages;
  int totalResults;

  factory Movie.fromJson(Map<String, dynamic> json) => Movie(
        page: json["page"],
        results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
        totalPages: json["total_pages"],
        totalResults: json["total_results"],
      );

  Map<String, dynamic> toJson() => {
        "page": page,
        "results": List<dynamic>.from(results.map((x) => x.toJson())),
        "total_pages": totalPages,
        "total_results": totalResults,
      };
}

class Result {
  Result({
    required this.adult,
    this.backdropPath,
    this.genreIds,
    this.id,
    this.originalLanguage,
    this.originalTitle,
    this.overview,
    this.popularity,
    this.posterPath,
    this.releaseDate,
    this.title,
    this.video,
    this.voteAverage,
    this.voteCount,
  });

  bool adult;
  String? backdropPath;
  List<int>? genreIds;
  int? id;
  String? originalLanguage;
  String? originalTitle;
  String? overview;
  double? popularity;
  String? posterPath;
  DateTime? releaseDate;
  String? title;
  bool? video;
  double? voteAverage;
  int? voteCount;

  factory Result.fromJson(Map<String, dynamic> json) => Result(
        adult: json["adult"],
        backdropPath: json["backdrop_path"],
        genreIds: List<int>.from(json["genre_ids"].map((x) => x)),
        id: json["id"],
        originalLanguage: json["original_language"],
        originalTitle: json["original_title"],
        overview: json["overview"],
        popularity: json["popularity"].toDouble(),
        posterPath: json["poster_path"],
        releaseDate: DateTime.parse(json["release_date"]),
        title: json["title"],
        video: json["video"],
        voteAverage: json["vote_average"].toDouble(),
        voteCount: json["vote_count"],
      );

  Map<String, dynamic> toJson() => {
        "adult": adult,
        "backdrop_path": backdropPath,
        "genre_ids": List<dynamic>.from(genreIds!.map((x) => x)),
        "id": id,
        "original_language": originalLanguage,
        "original_title": originalTitle,
        "overview": overview,
        "popularity": popularity,
        "poster_path": posterPath,
        "release_date": "${releaseDate!.year.toString().padLeft(4, '0')}-${releaseDate!.month.toString().padLeft(2, '0')}-${releaseDate!.day.toString().padLeft(2, '0')}",
        "title": title,
        "video": video,
        "vote_average": voteAverage,
        "vote_count": voteCount,
      };
}

添加了 github 链接以供参考https://github.com/nizamudeenms/ZlikxFlutter/

在 ID 为 385687 的Result object 中,您有一个属性 background_path 为backdrop_path 调整您的Result object 并使属性可为空:

String? backdropPath;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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