简体   繁体   中英

Error: Null check operator used on a null value - for boolean value - in Flutter

https://flutterigniter.com/checking-null-aware-operators-dart/

Null check operator used on a null value

These links say that if the value can be null then we can use ?? operator to assign a value to it. I tried it, it still shows the same error:

This is the data structure .

main.dart


import 'package:flutter/material.dart';
import 'dart:convert';

BigData bigDataFromJson(String str) => BigData.fromJson(json.decode(str));

class BigData {
  BigData({
    this.data,
  });
  Data? data;

  factory BigData.fromJson(Map<String, dynamic> json) => BigData(
        data: Data.fromJson(json["data"]),
      );

  Map<String, dynamic> toJson() => {
        "data": data!.toJson(),
      };
}

class Data {
  Data({
    this.lockoutDetails,
  });

  bool? lockoutDetails;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
        lockoutDetails: json["lockout_details"],
      );

  Map<String, dynamic> toJson() => {
        "lockout_details": lockoutDetails,
      };
}

Here from the default application of Flutter starts:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

Here I have used the variable lockoutDetails from the above datastructures and it shows the error null check operator used on a null value .

class _MyHomePageState extends State<MyHomePage> {
  BigData d = BigData();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child:       
        d.data!.lockoutDetails ?? true
          ? const Text(
              'AAA',
            )
          : Container(),
    ));
  }
}

What is the way to correct it?

d.data is null in this case, you can replace

 d.data!.lockoutDetails ?? true

with

 d.data?.lockoutDetails ?? true

Your d.data is null. For test run use d.data?.lockoutDetails .

Think to set data for to have value.

you can use ? instead of ! which means that it may or maynot be null. If you add ! you are mentioning that its not null but the value is unknown

d.data?.lockoutDetails ?? true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM