Search code examples
sqlitedatetimeflutterinstance

Create a DATETIME column in SQLite FLutter database?


I create a TABLE with some columns and everything's ok until I tried to insert a new DATETIME column:

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

My Model Class to store is:

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

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

In the controller, I tried to store a new instance of Pet, instantiating a new variable DateTime _date = new DateTime.now(); and saving all in

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

But when I insert in the database I receive:

Unhandled Exception: Invalid argument: Instance of 'DateTime'


Solution

  • You are passing DateTime object directly.

    Use class methods like:

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

    or

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

    You need to pass String or int instead of an Object. The reason being, you must use supported SQLite data types to store in a SQLite table, find a list of supported data types here https://www.sqlite.org/datatype3.html

    Also checkout:

    https://pub.dev/packages/sqflite

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

    To retrieve your DateTime object again:

    From Integer:

    DateTime.fromMillisecondsSinceEpoch(yourValue);
    

    From String:

    DateTime.parse(yourValue);
    

    or better way:

    DateTime.tryParse(yourValue);