How to use freezed with Firebase Geopoint datatype in flutter

48 Views Asked by At

I was having trouble finding how to use freezed with the GeoPoint data type for Firebase. There are a few questions along these lines that have been posted but they were too old to use the cloud_firestore_odm library to simplify the solution.

1

There are 1 best solutions below

0
Benjamin James On

This is the code that worked for me. The trick was to preface the Geopoint variable with the JSONConverter implementation from the cloud firestore ODM library:

// This file is "main.dart"
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
import 'package:cloud_firestore_odm/cloud_firestore_odm.dart';

// required: associates our `main.dart` with the code generated by Freezed
part 'site.freezed.dart';
// optional: Since our Client class is serializable, we must add this line.
// But if Client was not serializable, we could skip it.
part 'site.g.dart';

@freezed //run flutter pub run build_runner build to generate the related .freezed and .g classes
class Site with _$Site {
  const factory Site(
      {required String
          siteId, //This should give a description of the site, eg TheOffice@OfficeAddress, or WFH
      @FirestoreGeoPointConverter()
      GeoPoint?
          location, //To be used to provide a location for navigation to the site
      String? address //eg Level 3 153 Flinders Street
      }) = _Site;

  factory Site.fromJson(Map<String, Object?> json) => _$SiteFromJson(json);
}

I could then use "flutter pub run build_runner build" to run the freezed build and it all took care of iteself.