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

Create a DATETIME column in SQLite FLutter database?

我创建了一个包含一些列的 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 是:

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 对象。

使用 class 方法,例如:

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 而不是对象。原因是,您必须使用支持的 SQLite 数据类型存储在 SQLite table 中,请在此处找到支持的数据类型列表 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);