dart Flutter Rest API:空值[重复]上使用的空检查运算符

ekqde3dh  于 2023-09-28  发布在  Flutter
关注(0)|答案(1)|浏览(87)

此问题已在此处有答案

Null check operator used on a null value(14个回答)
14天前关闭
我开始学习Rest API。我在做一个翻新的酒店应用。我用数据创建模型,当我添加ListView.builder时,它返回错误。
用于空值的空校验运算符
我不确定是因为数据模型有错误还是其他原因。

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

lp0sw83n1#

null check是-> <Nullable>!,意思是,你告诉dart分析器这个值不会为null,所以分析器不会抱怨。
但稍后在编译时,Nullable的实际值为null,dart将抛出null check, use on null value
举个例子:

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);
          }

让我们尝试打印print(snapshots.data),如果结果为null,那么它仍然可以为null。所以我们必须处理这个条件:

List<HotelModel> hotels = [];
final data = snapshots.data;
if(data != null){
   hotels = data;
}
        return _hotels(hotels);

相关问题