I am currently creating a database using Isar that looks like this:
@collection
class Polygon {
Id id = Isar.autoIncrement;
final vertices = IsarLinks<Vertex>();
late Color color;
}
@collection
class Vertex {
Id id = Isar.autoIncrement;
final polygon = IsarLink<Polygon>();
late Offset point;
}
In my code, I've got an image I'm drawing these polygons onto using a GestureDetector onTapUp event to do:
List<Vertex>? _currentVertices;
void addVertex(details) async {
Offset pos = details.localPosition;
if (_currentVertices == null) {
_currentVertices = [Vertex()..point = pos];
} else {
if (_currentVertices!.length > 2 &&
(_currentVertices!.first.point - pos).distance <= 20 ) {
// Create a new polygon from the list of vertices and save it to the database
Polygon p = Polygon();
// Set the polygon for each vertex
for (var v in _currentVertices!) {
v.polygon.value = p;
}
// Save it into the database
await _isar.writeTxn(() async {
await _isar.polygons.put(p);
});
_currentVertices = null;
} else {
// Add point to current list of vertices
_currentVertices!.add(Vertex()..point = pos);
}
}
}
But, when I do this, the Polygon will appear in the database, but the vertices do not. So I tried:
await _isar.writeTxn(() async {
await _isar.polygons.put(p);
});
for (var v in _currentVertices!) {
await _isar.writeTxn(() async {
await _isar.vertexs.put(v);
});
}
Now both the polygons and the vertices are in the database, but the id's / IsarLinks are not set...
- Does anyone have an example of how you should do this?
Secondly:
I've actually been reading about instead using a provider here (inside a PolygonModel class). So once I have my PolygonModel class (that my view can watch for changes to the polygons), I need to have a method PolygonModel.addPolygon(p).
Should I implement both the Polygon model and Vertex model? I don't actually need a Vertex model as a change notifier, so it feels like overkill. So should I just do:
// Create a new polygon from the list of vertices and save to the database
Polygon p = Polygon();
for (var v in _currentVertices!) {
v.polygon.value = p;
}
// Add both the polygon and vertices to the database
polygonModel.addPolygon(p, _currentVertices!);
Or do I actually need to do something like:
// Create a new polygon from the list of vertices and save to the database
Polygon p = Polygon();
polygonModel.addPolygon(p);
for(var v in _currentVertices!) {
vertexModel.addVertex(p, v);
}
Again, any links to suitable examples of a similar implementation would be great (currently I was going to use provider/provider.dart, but have also been reading about Riverpod, which may be a better solution).