Home > Net >  Fetch data from API, but the list is empty, it used to work 30 mins ago
Fetch data from API, but the list is empty, it used to work 30 mins ago

Time:02-10

Fetching from the api should be right, but it's not working since my list of "_movies" is empty. It was good looking application 2 hours ago and i dont know what i changed to do this. It returns either nothing when itemCount:_movies.length or error "invalid value: valid value range is empty: 0. I'm stuck on this.

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,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }
}

seems like _movies.lenght is 0, but somehow it worked right 2 hours ago and i didnt change a thing

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"]);
  }
}

CodePudding user response:

I believe the error must be on this line:

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

I think dart is confused about rebuilding the _movies variable because you are modifying it instead of reassigning it. If I am right, the solution is as simple as reassigning _movies:

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