Home > database >  NoSuchMethodError: 'cast' with dart language
NoSuchMethodError: 'cast' with dart language

Time:09-05

i'm following flutter offical docs to parse JSON in the background with the rest api from themoviedb. I get this following error when trying to show the list of movies enter image description here the api link : trending movie

app.dart' simplify main.dart and isolate parsing using compute

import 'dart:convert';
import 'package:flutter/material.dart';
import 'models/movie_response.dart';
import 'package:auth_request/api_key.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

Future<List<Movie>> fetchMovies(http.Client client) async {
  final response = await client
      .get(Uri.parse('https://api.themoviedb.org/3/trending/movie/week?api_key=$apiKey')); 


    // Use the compute funtion to run fetchMovies in a separate isolate
    return compute(parseMovies, response.body);
}
// A function that converts a response body into a List<Movie>.
List<Movie> parseMovies(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Movie>((json) => Movie.fromJson(json)).toList();
}
 
class MovieApp extends StatefulWidget {
  const MovieApp({super.key});

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

class MovieAppState extends State<MovieApp> {
  late Future<Movie> futureAlbum;

  @override
  void initState() {
    super.initState(); 
  }
  
  @override
  Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'MovieDB List',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('MovieDB List'),
        ),
        body: Center( 
          child: FutureBuilder<List<Movie>>(
            future: fetchMovies(http.Client()),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return Text('${snapshot.error}');
                
              } else if (snapshot.hasData) { 
                return MoviesList(movies: snapshot.data!);
          } else {
            return  const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    ),
      ),
    );
  }
}

// 
class MoviesList extends StatelessWidget {
  const MoviesList({super.key, required this.movies});

  final List<Movie> movies;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ), 
      itemBuilder: (context, index) {
        return Image.network(movies[index].original_title);
      },
    );
  }
}

movie.dart

Parse and convert the JSON into a list of movies with the help of map and factory

  class Movie {    
  final String original_title;
  final String overview;
  final String poster_path; 
  final String release_date;
  

  const Movie({    
    required this.original_title,
    required this.overview,
    required this.poster_path,
    required this.release_date, 
  });

  factory Movie.fromJson(Map<String, dynamic> json) {
    return Movie(     
      original_title: json['original_title'],
      overview: json['overview'],
      poster_path: json['poster_path'], 
      release_date: json['release_date'],
    );
  }
}

CodePudding user response:

change this:

final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

to

final parsed = jsonDecode(responseBody)['results'];
  • Related