Carl.G
Carl.G

Reputation: 309

Flutter Hive Adapter for Geopoint

I'm storing a geopoint in firestore and I'm trying to retrieve it with my Hive adapter. However, Im getting

Cannot write, unknown type: GeoPoint. Did you forget to register an adapter?

I'm registering the adapter so that's not the issue. is the geopoint part of the data.

This is my hive field

@HiveField(5)
  Map<String, dynamic> location;

This is how it looks in my Firestore DB

enter image description here

Has anybody faced this issue or there a way to create an adapter for this to be used by Hive/Firestore?

Upvotes: 0

Views: 791

Answers (1)

derZorn
derZorn

Reputation: 254

To create a Gepoint Adapter you need to have a model that can be adapted. I am not sure how you handle the data stored in that geopoint, and I guess I would simply parse the data in some way. So I am assuming this model:

import 'package:hive/hive.dart';

part 'location.g.dart';

@HiveType(typeId: 0)
class Location {
  @HiveField(0)
  String geohash;

  @HiveField(1)
  GeoPoint geoPoint;

  @HiveField(2)
  String locationPreviewURL;
}

Notice the part 'location.g.dart'; . This will be used by the generator to create an adapter in the end.

Create a model for GeoPoint containing Types Hive can handle, so I am assuming the geodata part of your value is a String for now. You need to decide how to handle that type of value. I'll focus on the adapter part for now.

import 'package:hive/hive.dart';

part 'geopoint.g.dart';

@HiveType(typeId: 1)
class GeoPoint {
  @HiveField(0)
  String geodata;
}

With that in place, go to your terminal and run

flutter packages pub run build_runner build

to create the adapters. Note that you will need to recreate those when you change the HiveModels . You should use

flutter packages pub run build_runner build --delete-conflicting-outputs

for that.

Finally you need to register your Adapters so Hive can make use of them. So before opening any boxes, usually when initializing the app call

Hive.registerAdapter(LocationAdapter());
Hive.registerAdapter(GeoPointAdapter());

Upvotes: 0

Related Questions