【问题标题】:'String' is not a subtype of type 'bool'“字符串”不是“布尔”类型的子类型
【发布时间】:2020-01-08 03:21:15
【问题描述】:

这是一个使用数据库的待办事项列表应用程序。我正在使用布尔变量isDone 将任务标记为完成,但是当我添加新任务时,我收到错误'String' is not a subtype of type 'bool'。我想将isDone 的值更改为字符串,但我不确定我可以在哪里输入.toString() 行。

尝试使用类似错误的解决方案(int、bool、future 不是 string、bool 等的子类型),但由于这些错误是特定于应用程序的,因此无法解决。

数据库代码:

 //This is the database

  String _itemName;
  String _dateCreated;
  int _id;
  bool _isDone;


  TodoItem(this._itemName, this._dateCreated, this._isDone);

  TodoItem.map(dynamic obj) {
    this._itemName = obj["itemName"];
    this._dateCreated = obj["dateCreated"];
    this._id = obj["id"];
    this._isDone = obj["isDone"];
  }

  String get itemName => _itemName;
  String get dateCreated => _dateCreated;
  int get id => _id;
  bool get isDone => _isDone;
  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    map["itemName"] = _itemName;
    map["dateCreated"] = _dateCreated;
    map["isDone"] = _isDone;

    if (_id != null) {
      map["id"] = _id;
    }

    return map;
  }

  TodoItem.fromMap(Map<String, dynamic> map) {
    this._itemName = map["itemName"];
    this._dateCreated = map["dateCreated"];
    this._id = map["id"];
    this._isDone = map["isDone"];
  }

数据库创建、更新功能:

注意:更新函数只应该改变 isDone 的值

 Future<bool> updateItem(TodoItem item) async {
    var dbClient = await db;
    int res =   await dbClient.update("id", item.toMap(),
        where: "id = ?", whereArgs: <bool>[item.isDone]);
    return res > 0 ? true : false;
  }
  Future<int> saveItem(TodoItem item) async {
    var dbClient = await db;
    int res = await dbClient.insert("$tableName", item.toMap());
    print(res.toString());
    return res;
  }

【问题讨论】:

  • 你能不能也发布那个 json,可能 ne map["isDone"] 会以字符串形式出现,例如 e.x "true"
  • sqflite 不支持布尔值。它将布尔值存储为 1 或 0(即 int 的形式)。尝试使用 而不是 。请让我知道它是否有效与否。

标签: database flutter sqflite


【解决方案1】:

当 bool x = string value 在代码中分配时,Flutter 会出现此错误。不幸的是,在 Dart 中没有从字符串到布尔的转换。一个简单的技巧是放这样的东西

String test = "true";
bool isCorrect = test == 'true';

这按预期工作,因为代码会将 string 和 bool 的值作为字符串进行比较,并将结果作为 bool 返回。在上面代码的第二行之前,您可能需要根据您的字符串值使用 .toLowerCase() 或 .toUpperCase() 。

【讨论】:

    【解决方案2】:

    boolnot supported in SQLite

    可能发生的情况是isDone 列值true 被转换为字符串"true",因此它在您的TodoItem.map 构造函数中崩溃。

    尝试在插入之前或在查询参数中将值转换(并解析)为 1 或 0 (int)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 2017-12-28
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      • 2020-02-07
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多