Home > Enterprise >  Flutter: type 'Null' is not a subtype of type 'bool'
Flutter: type 'Null' is not a subtype of type 'bool'

Time:12-06

I try to change my checkbox from false to true when it clicked but it return null is not a subtype of type bool.

Here's my code:

   // my function for checkbox
  void checkBoxChanged(bool? value, int index) {
    setState(() {
      db.folderTask[index].isChecked = !db.folderTask[index].isChecked;
    });
    db.updateDatabase();
  }

The error is here:

class FolderTask {
  String? name;
  bool isChecked = false;
  FolderTask({required this.name, required this.isChecked});
  factory FolderTask.fromJson(json) {
    return FolderTask(name: json['name'], isChecked: json['isChecked']);
  }
  Map<String, dynamic> toJson() => {
        "name": name,
        "task": [isChecked]
      };
}

CodePudding user response:

You can provide default value on null case like,

return FolderTask(name: json['name'], isChecked: json['isChecked']??false);

CodePudding user response:

It looks like the issue is with the isChecked property of the FolderTask class. In the constructor for the FolderTask class, you have declared the isChecked parameter as required, but in the fromJson factory method, you are not providing a value for the isChecked property when creating a new FolderTask instance from a JSON object.

To fix this issue, you can either remove the required keyword from the isChecked parameter in the constructor, or you can provide a default value for the isChecked property in the fromJson method.

Here's an example of how you can update the FolderTask class to fix this issue:

  String? name;
  bool isChecked = false;

  FolderTask({required this.name}); // remove the required keyword from isChecked

  factory FolderTask.fromJson(json) {
    return FolderTask(
      name: json['name'],
      isChecked: json['isChecked'] ?? false, // provide a default value for isChecked
    );
  }

  Map<String, dynamic> toJson() => {
        "name": name,
        "task": [isChecked]
      };
}

Alternatively, you could provide a default value for the isChecked property in the constructor, like this:

  String? name;
  bool isChecked = false;

  FolderTask({required this.name, this.isChecked = false}); // provide a default value for isChecked

  factory FolderTask.fromJson(json) {
    return FolderTask(
      name: json['name'],
      isChecked: json['isChecked'],
    );
  }

  Map<String, dynamic> toJson() => {
        "name": name,
        "task": [isChecked]
      };
}

Either of these approaches should fix the issue and allow you to toggle the isChecked property of the FolderTask class without encountering the "null is not a subtype of type bool" error.

I hope this helps!

  • Related