我创建了一个包含一些列的 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
您需要传递 String
或 int
而不是 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/