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
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:
lets try to print that
print(snapshots.data)
if the result is null then its still nulable. so we must handle the condition: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: