You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何结合freezed使用Firebase GeoPoint数据类型?

在Flutter中结合Freezed使用Firebase GeoPoint的解决方案

1. 定义GeoPoint转换器(用于JSON序列化)

如果需要将Freezed对象序列化为JSON(比如本地存储或API传输),需自定义JsonConverter处理GeoPoint与Map的互转:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';

class GeoPointConverter implements JsonConverter<GeoPoint, Map<String, dynamic>> {
  const GeoPointConverter();

  @override
  GeoPoint fromJson(Map<String, dynamic> json) {
    return GeoPoint(json['latitude'] as double, json['longitude'] as double);
  }

  @override
  Map<String, dynamic> toJson(GeoPoint object) {
    return {
      'latitude': object.latitude,
      'longitude': object.longitude,
    };
  }
}

2. 创建Freezed数据类

在Freezed类中直接用GeoPoint作为字段类型,为需要JSON序列化的字段添加转换器注解:

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

part 'place.freezed.dart';
part 'place.g.dart';

@freezed
class Place with _$Place {
  const factory Place({
    required String id,
    required String name,
    // 仅需JSON序列化时添加该注解,Firestore读写可直接用原生GeoPoint
    @GeoPointConverter() required GeoPoint location,
  }) = _Place;

  // JSON序列化方法
  factory Place.fromJson(Map<String, dynamic> json) => _$PlaceFromJson(json);

  // 从Firestore DocumentSnapshot直接转换的方法
  factory Place.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
    final data = doc.data()!;
    return Place(
      id: doc.id,
      name: data['name'],
      location: data['location'] as GeoPoint,
    );
  }

  // 转换为Firestore可接受的Map(直接使用原生GeoPoint)
  Map<String, dynamic> toFirestore() {
    return {
      'name': name,
      'location': location,
    };
  }
}

3. Firestore读写示例

写入数据

final place = Place(
  id: 'place_1',
  name: 'Central Park',
  location: GeoPoint(40.7812, -73.9665),
);

await FirebaseFirestore.instance
    .collection('places')
    .doc(place.id)
    .set(place.toFirestore());

读取数据

final doc = await FirebaseFirestore.instance
    .collection('places')
    .doc('place_1')
    .get();

final place = Place.fromFirestore(doc);

注意事项

  • 若无需JSON序列化,可去掉GeoPointConverter和fromJson方法,直接通过fromFirestore和toFirestore处理Firestore读写,更简洁。
  • 确保cloud_firestore依赖版本与项目兼容,避免类型不匹配问题。

内容的提问来源于stack exchange,提问作者Benjamin James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:35:18