dart 从API中获取数据,但列表为空,30分钟前它可以正常工作

ecbunoof  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(103)

从API获取应该是正确的,但它不起作用,因为我的“_movies”列表是空的。两个小时前,它还是很好看的应用程序,我不知道我做了什么改变来做到这一点。
itemCount:_movies.length或error时,它将不返回任何内容:
“无效值:有效值范围为空:0.
我被困在这了。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:task/models/movies.dart';
import 'package:http/http.dart' as http;

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Movie> _movies = <Movie>[];
  var moviesUrl =
      'https://raw.githubusercontent.com/FEND16/movie-json-data/master/json/movies-coming-soon.json';
  Future<List<Movie>> getMovies() async {
    http.Response res = await http.get(Uri.parse(moviesUrl));
    try {
      if (res.statusCode == 200) {
        List<dynamic> movies = json.decode(res.body);
        return movies.map((e) => Movie.fromJson(e)).toList();
      } else {
        return <Movie>[];
      }
    } catch (e) {
      // print(e);
      return <Movie>[];
    }
  }

  @override
  void initState() {
    getMovies().then((value) {
      setState(() {
        _movies.addAll(value);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Movies"),
      ),
      body: ListView.builder(
          itemCount: _movies.length,
          itemBuilder: (context, index) {
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      _movies[index].title,
                      style:
                          TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                    ),
                    Text(
                      _movies[index].genres.toString(),
                      style: TextStyle(
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }
}

字符串
看起来_movies.length是0,但不知何故,它在两个小时前就工作了,我没有改变任何东西。

class Movie {
  String id;
  String title;
  String year;
  List genres;
  // List ratings;
  String poster; //image
  // String contentRating;
  String duration;
  // DateTime releaseDate;
  // int averageRating;
  String originalTitle;
  String storyline;
  List actors;
  // String imdbRating;
  String posterurl; //image

  Movie({
    required this.id,
    required this.title,
    required this.year,
    required this.genres,
    // required this.ratings,
    required this.poster,
    // required this.contentRating,
    required this.duration,
    // required this.releaseDate,
    // required this.averageRating,
    required this.originalTitle,
    required this.storyline,
    required this.actors,
    // required this.imdbRating,
    required this.posterurl,
  });

  factory Movie.fromJson(Map<String, dynamic> json) {
    return Movie(
        id: json["id"],
        title: json["title"],
        year: json["year"],
        genres: json["genres"],
        // ratings: json["ratnigs"],
        poster: json["poster"],
        // contentRating: json["contentRating"],
        duration: json["duration"],
        // releaseDate: json["releaseDate"],
        // averageRating: json["averageRating"],
        originalTitle: json["originalTitle"],
        storyline: json["storyline"],
        actors: json["actors"],
        // imdbRating: json["imdbRating"],
        posterurl: json["posterurl"]);
  }
}

6mw9ycah

6mw9ycah1#

我相信错误一定在这一行:

getMovies().then((value) {
  setState(() {
    _movies.addAll(value);
  });
});

字符串
我认为dart对重建_movies变量感到困惑,因为您正在修改它而不是重新分配它。如果我是对的,解决方案就像重新分配_movies一样简单:

getMovies().then((value) {
  setState(() {
    _movies = [..._movies, ...value]
  });
});

相关问题