'How is the 'id' Field Handled by SQFlite Flutter Package During an Insert?
This question has to do with the sqflite Flutter package, the "id" field, and how that affects null safe coding choices in the data model.
Consider the following (working fine) code:
class User {
final int? id;
final String name;
final int age;
final String country;
final String? email;
User(
{ this.id,
required this.name,
required this.age,
required this.country,
this.email});
User.fromMap(Map<String, dynamic> res)
: id = res["id"],
name = res["name"],
age = res["age"],
country = res["country"],
email = res["email"];
Map<String, Object?> toMap() {
return {'id':id,'name': name, 'age': age, 'country': country, 'email': email};
}
}
So this is our User "model."
The toMap() function comes into play when we do the following (psuedo code):
User newUser = new User(...);
Database.insert(MY_TABLE, newUser.toMap());
Am I correct in the following:
The reason that the User.id field is optional (nullable) is because it is actually the primary key in MY_TABLE and therefore pointless to define when creating a new user.
When inserting a user, sqflite will either A) if id is null, generate a new id, then insert or B) if id is not null, attempt to insert using that id.
Or is it C) the id is always ignored and generated on insert?
I tried looking through the source code but I can't find it the part I'm looking for.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
