Edo*_*lla 7 sqlite datetime instance flutter
我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)");
}
Run Code Online (Sandbox Code Playgroud)
我要存储的模型类是:
class Pet {
int id;
String name;
DateTime birth;
String breed;
String colour;
Pet({this.id, this.name, this.birth, this.colour, this.breed});
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,我尝试存储 的新实例Pet,实例化一个新变量DateTime _date = new DateTime.now();并将所有内容保存在
Pet newPet = Pet(
id: null,
name: _name,
colour: _colour,
breed: _breed,
birth: _date
);
Run Code Online (Sandbox Code Playgroud)
但是当我插入数据库时,我收到:
未处理的异常:无效参数:“DateTime”的实例
Ese*_*met 20
可能你是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代替对象。原因是,您必须使用支持的 SQLite 数据类型存储在 SQLite 表中,在此处找到支持的数据类型列表https://www.sqlite.org/datatype3.html
还结帐:
https://pub.dev/packages/sqflite
DateTime 不是受支持的 SQLite 类型。我个人将它们存储为 int (millisSinceEpoch) 或 string (iso8601)
DateTime再次检索您的对象:
从整数:
DateTime.fromMillisecondsSinceEpoch(yourValue);
Run Code Online (Sandbox Code Playgroud)
从字符串:
DateTime.parse(yourValue);
Run Code Online (Sandbox Code Playgroud)
或更好的方法:
DateTime.tryParse(yourValue);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12273 次 |
| 最近记录: |