sqlite - 在 SQLite FLutter 数据库中创建 DATETIME 列?

标签 sqlite datetime flutter instance

我创建了一个包含一些列的 TABLE,一切正常,直到我尝试插入一个新的 DATETIME 列:

_onCreate(Database db, int version) async {
await db.
execute("CREATE TABLE $TABLE ($ID INTEGER PRIMARY KEY, $NAME TEXT, $COLOUR 
TEXT, $BREED TEXT, $BIRTH DATETIME)");
}

我要存储的模型类是:

class Pet {
 int id;
 String name;
 DateTime birth;
 String breed;
 String colour;

 Pet({this.id, this.name, this.birth, this.colour, this.breed});
 }

在 Controller 中,我尝试存储一个新的Pet实例,实例化一个新的变量DateTime _date = new DateTime.now();,并全部保存在

Pet newPet = Pet(
      id: null,
      name: _name,
      colour: _colour,
      breed: _breed,
      birth: _date
  );

但是当我插入数据库时​​,我收到:

Unhandled Exception: Invalid argument: Instance of 'DateTime'

最佳答案

您正在直接传递 DateTime 对象。

使用类方法如:

https://api.dart.dev/stable/2.9.3/dart-core/DateTime/millisecondsSinceEpoch.html

https://api.dartlang.org/stable/2.4.0/dart-core/DateTime/toIso8601String.html

您需要传递 Stringint 而不是 Object。原因是,您必须使用受支持的 SQLite 数据类型存储在 SQLite 表中,请在此处找到受支持数据类型的列表 https://www.sqlite.org/datatype3.html

同时结帐:

https://pub.dev/packages/sqflite

DateTime is not a supported SQLite type. Personally I store them as int (millisSinceEpoch) or string (iso8601)

要再次检索您的 DateTime 对象:

来自整数:

DateTime.fromMillisecondsSinceEpoch(yourValue);

来自字符串:

DateTime.parse(yourValue);

或更好的方法:

DateTime.tryParse(yourValue);

关于sqlite - 在 SQLite FLutter 数据库中创建 DATETIME 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57165310/

相关文章:

sql - Flutter - SQLite 死锁只是在应用程序的第一次运行中

sqlite - 在 sqlite 中拆分列值

ios - 滚动到 View 中时,菜单的屏幕外文本会出现延迟 - WebView 问题? (iOS)

encryption - System.Data.SQLite 使用什么类型/级别的密码加密

Ruby - 选择具有最新日期的数组条目

php - 空 DATETIME 值存储为 0000-00-00 00 :00:00 instead of NULL in MySQL

flutter - 如何在 Dart 中迭代流

ruby-on-rails - Rails API - 将 .includes() 结果限制为仅最新创建的记录

javascript - 在 Cosmos DB 存储过程中创建和比较日期

api - flutter : How To Convert Future<String> to String?