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()
]);
});
}
}
>Solution :
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);