Home > Back-end >  Error: Null check operator used on a null value - for boolean value - in Flutter
Error: Null check operator used on a null value - for boolean value - in Flutter

Time:07-05

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?

CodePudding user response:

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

CodePudding user response:

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

 d.data!.lockoutDetails ?? true

with

 d.data?.lockoutDetails ?? true

CodePudding user response:

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

Think to set data for to have value.

  • Related