skip to Main Content

I started learning Rest Api. I was creating hotel app with retrofit. I created Model with data, when i added ListView.builder it returned error.

Null check operator used on a null value

I’m not sure if it’s because Data model has an error or other cause.

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hotelapp/models/hotel_screen.dart';
import 'package:hotelapp/service/api_service.dart';

import '../../consts/color_palette.dart';

class HotelPage extends StatelessWidget {
  const HotelPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Отель',
          style: TextStyle(color: Colors.black),
        ),
        toolbarHeight: 50,
        backgroundColor: backgroundtheme,
        elevation: 0,
      ),
      body: _body()
    );
  }
  FutureBuilder _body() {
    final apiService = ApiService(Dio(BaseOptions(contentType: "application/json")));
    return FutureBuilder(future: apiService.getHotels(), builder: (context, snapshots) {
      if (snapshots.connectionState == ConnectionState.done) {
        final List<HotelModel> hotels = snapshots.data!;
        return _hotels(hotels);
      }
      else {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
    });
  }


// This where error happens

  Widget _hotels(List<HotelModel> hotels) {
    return ListView.builder(
      itemCount: hotels.length,
        itemBuilder: (context, index) {
      return const Stack(children: [
        Column(
          children: [
            HotelScreen(),
            HotelDescription(),
          ],
        ),
        BottomButtonWidget()
      ]);
    });
  }
}

2

Answers


  1. null check is -> <Nullable>!, is mean, you tell dart analizer this value will not be null, so analizer will not complain about it.

    but later when compiling the Nullable actual value is null, and dart will throw null check, use on null value.

    lets take an example:

     if (snapshots.connectionState == ConnectionState.done) {
                final List<HotelModel> hotels = snapshots.data!; <- use a null check here, 
    because we sure it will not be null right? ... or maybe not?
                return _hotels(hotels);
              }
    

    lets try to print that print(snapshots.data) if the result is null then its still nulable. so we must handle the condition:

    List<HotelModel> hotels = [];
    final data = snapshots.data;
    if(data != null){
       hotels = data;
    }
            return _hotels(hotels);
    
    Login or Signup to reply.
  2. The error message "Null check operator used on a null value" typically occurs when you try to access a property or method on a null object. In your code, this error is likely happening because snapshots.data is null in some cases.

    To fix this issue, you should ensure that you handle the case when snapshots.data is null properly. You can use a conditional check to handle this situation. Here’s how you can modify your code:

    FutureBuilder _body() {
      final apiService = ApiService(Dio(BaseOptions(contentType: "application/json")));
      return FutureBuilder(
        future: apiService.getHotels(),
        builder: (context, snapshots) {
          if (snapshots.connectionState == ConnectionState.done) {
            if (snapshots.hasData) {
              final List<HotelModel> hotels = snapshots.data!;
              return _hotels(hotels);
            } else {
              // Handle the case when data is null (if needed)
              return const Center(
                child: Text("No data available"), // or any other appropriate message
              );
            }
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search