Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading