skip to Main Content

Receiving this error _CastError (Null check operator used on a null value), tried replacing ! with ? but that doesn’t work.

Please help me fix this issue, Thanks.

error

home_screen.dart

import 'package:flutter/material.dart';
import 'package:mvvm/data/response/status.dart';
import 'package:mvvm/model/movies_model.dart';
import 'package:mvvm/utils/routes/routes_names.dart';
import 'package:mvvm/view_model/home_view_model.dart';
import 'package:mvvm/view_model/user_view_model.dart';
import 'package:provider/provider.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  HomeViewModel homeViewModel = HomeViewModel();

  @override
  void initState() {
    // TODO: implement initState
    homeViewModel.fetchMoviesListApi();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final userPreferences = Provider.of<UserViewModel>(context);
    return Scaffold(
      appBar: AppBar(
        // removes back button
        automaticallyImplyLeading: false,
        actions: [
          InkWell(
            onTap: () {
              userPreferences.removeUser().then((value) {
                Navigator.pushNamed(context, RoutesNames.login);
              });
            },
            child: const Center(
                child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: Text(
                "Logout",
                style: TextStyle(fontSize: 20),
              ),
            )),
          ),
          const SizedBox(height: 20)
        ],
      ),
      body: ChangeNotifierProvider<HomeViewModel>(
        create: (BuildContext context) => homeViewModel,
        child: Consumer<HomeViewModel>(
          builder: ((context, value, _) {
            switch (value.moviesList.status) {
              case Status.LOADING:
                return const Center(child: CircularProgressIndicator());
              case Status.ERROR:
                return Text(value.moviesList.message.toString());
              case Status.COMPLETED:
                return ListView.builder(
                  // itemCount: value.moviesList.data?.movies?.length,
                  itemCount: value.moviesList.data?.movies?.length,
                  itemBuilder: ((context, index) {
                    return Card(
                      child: ListTile(
                       title: Text((value.moviesList.data!.movies![index].title.toString()),),
                      ),
                    );
                  }),
                );
            }
            return Container();
          }),
        ),
      ),
    );
  }
}

movies_model.dart

class MovieListModel {
  List<Movies>? movies;

  MovieListModel({this.movies});

  MovieListModel.fromJson(Map<String, dynamic> json) {
    if (json['movies'] != null) {
      movies = <Movies>[];
      json['movies'].forEach((v) {
        movies!.add(new Movies.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.movies != null) {
      data['movies'] = this.movies!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Movies {
  String? title;
  String? year;
  String? runtime;
  String? poster;

  Movies({this.title, this.year, this.runtime, this.poster});

  Movies.fromJson(Map<String, dynamic> json) {
    title = json['Title'];
    year = json['Year'];
    runtime = json['Runtime'];
    poster = json['Poster'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Title'] = this.title;
    data['Year'] = this.year;
    data['Runtime'] = this.runtime;
    data['Poster'] = this.poster;
    return data;
  }
}

api_response.dart

import 'package:mvvm/data/response/status.dart';

class ApiResponse<T> {
  Status? status;
  T? data;
  String? message;

  ApiResponse(this.status, this.data, this.message); // constructor

  ApiResponse.loading() : status = Status.LOADING;
  ApiResponse.completed(this.data) : status = Status.COMPLETED;
  ApiResponse.error(this.message) : status = Status.ERROR;

  @override
  String toString() {
    return "Status : $status n Message : $message n Data: $data ";
  }
}

2

Answers


  1. A quick solution will be accepting and rendering null on text widget like

    Text("${value.moviesList.data?.movies?[index].title}")
    

    The error referring your movies is getting null. If homeViewModel.fetchMoviesListApi(); is future, you may start using FutureProvider/FutureBuilder.

    Find more about null-safety.

    Login or Signup to reply.
  2. You can try

    String text = value.moviesList.data?.movies?[index].title ?? " I am null fix me"
    
    return Card(child: ListTile(
                     title: Text(text)),
           );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search