Search code examples
fluttersqflite

Flutter SQL Numeric DB Field error 'String' is not a subtype of type 'int?'


I am using Flutter SQFLite DB.

SQFLite Database does not allow Bool Types.

Hence, I need to save Bool values as Integer Zero and One.

Issue: I am getting the following runtime error:

Unhandled Exception: type 'String' is not a subtype of type 'int?' in type cast

The error shows the line from myFlag class -> isFlag: json[FlagFields.myFlag] as int?

Could you please point out the cause of the issue. Thank You

The Model Code:

(In FlagFields class, the field myFlag is String b/c I use it as Column Heading and the MyFlag class has the field isFlag which is int)

final String myFlagTable = 'myFlag';

class FlagFields {
  static final List<String> values = [id, myFlag];
  static final String id = '_id'; // SQL convention
  static final String myFlag = 'isFlag';
}

class myFlag {
  late final int? id;
  late int? isFlag = 0;
  myFlag({required this.id, required this.isFlag});
  myFlag copy({int? id, int? isFlag}) => myFlag(id: id ?? this.id, isFlag: isFlag ?? this.isFlag);
  Map<String, Object?> toJson() => {if (id != null) FlagFields.id: id, FlagFields.myFlag: isFlag};
  static myFlag fromJson(Map<String, Object?> json) => myFlag(
      id: json[FlagFields.id] as int?,
      isFlag: json[FlagFields.myFlag] as int?);
}

Solution

  • It seems the error was caused by an incorrect of fromJson method in your myFlag class. When you call fromJson on a Map<String, Object?>, you are assuming that the value associated with the "isFlag" key is an int?.but, since you are storing the value as a String in the database, you need to convert it to an int? before you can use it.

    here is the code could help you:

    static myFlag fromJson(Map<String, Object?> json) => myFlag(
          id: json[FlagFields.id] as int?,
          isFlag: int.tryParse(json[FlagFields.myFlag] as String?) ?? 0);