booking_calendar icon indicating copy to clipboard operation
booking_calendar copied to clipboard

Problem with method SportBooking.fromJson and ApiRepository

Open JoanFerrando64 opened this issue 2 years ago • 5 comments

Hi! I'm trying to implement your work to my project, and I've followed the example you give of Google Firebase with SportBooking. But there is something that I can't make sense of right now (maybe sleeping too little lol).

In the factory method factory SportBooking.fromJson(Map<String, dynamic> json) => _$SportBookingFromJson(json);

What does _$SportBookingFromJson mean? I can't find it declared in your example or anywhere else, and I would like to know how to declare it so that everything works.

errorFlutter

Also, I can't find a way to instance ApiRepository, and I can't find it to be a dependency. I would like to know what it refers to, if it is necessary or if I should implement it myself.

errorFlutterTwo

Thanks for your patience!

JoanFerrando64 avatar Dec 16 '22 00:12 JoanFerrando64

Hi @JoanFerrando64 , sorry for my delay, I am back.

So, the _$SportBookingFromJson is coming from the code generation, check out the docs: https://pub.dev/packages/json_serializable#example (you will need build_runner as well for codegeneration, I recommend this, can save you a lot of time)

The ApiRepository, is just a wrapper, so our business logic will not contain everything, we try to seperate our code, to be more maintanable, testable etc. Nothing magic happens really there, these are not neccessary, but it makes your code better and readable.

I will share these two methods, but you can do your own way as well.

 CollectionReference bookings = FirebaseFirestore.instance.collection('bookings');

bookings.doc(placeId).collection('bookings').withConverter<SportBooking>(
          fromFirestore: (snapshots, _) => SportBooking.fromJson(snapshots.data()!),
          toFirestore: (snapshots, _) => snapshots.toJson(),
        ).where('bookingStart', isGreaterThanOrEqualTo: startOfDay)
                        .where('bookingStart', isLessThanOrEqualTo: endOfDay)
                        .snapshots(),

The generated code:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'sport_booking.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

SportBooking _$SportBookingFromJson(Map<String, dynamic> json) => SportBooking(
      email: json['email'] as String?,
      phoneNumber: json['phoneNumber'] as String?,
      placeAddress: json['placeAddress'] as String?,
      bookingStart:
          AppUtil.timeStampToDateTime(json['bookingStart'] as Timestamp),
      bookingEnd: AppUtil.timeStampToDateTime(json['bookingEnd'] as Timestamp),
      placeId: json['placeId'] as String?,
      userId: json['userId'] as String?,
      userName: json['userName'] as String?,
      serviceName: json['serviceName'] as String?,
      serviceDuration: json['serviceDuration'] as int?,
      servicePrice: json['servicePrice'] as int?,
    );

Map<String, dynamic> _$SportBookingToJson(SportBooking instance) =>
    <String, dynamic>{
      'userId': instance.userId,
      'userName': instance.userName,
      'placeId': instance.placeId,
      'serviceName': instance.serviceName,
      'serviceDuration': instance.serviceDuration,
      'servicePrice': instance.servicePrice,
      'bookingStart': AppUtil.dateTimeToTimeStamp(instance.bookingStart),
      'bookingEnd': AppUtil.dateTimeToTimeStamp(instance.bookingEnd),
      'email': instance.email,
      'phoneNumber': instance.phoneNumber,
      'placeAddress': instance.placeAddress,
    };

Hope it helped, let me know if you have any questions.

FYI: I will build a complete Firebase example, which will be added to the examples, because looks like the current documentation is not enough for building a project with Firebase.

radikris avatar Jan 02 '23 08:01 radikris

Happy new year Waiting new complete documentation with firebase

helloooo avatar Jan 02 '23 08:01 helloooo

I will graduate university next week, after that I will make this happen!

radikris avatar Jan 02 '23 08:01 radikris

build_runner as well for codegener

Hello, I have a question. CollectionReference bookings = FirebaseFirestore.instance.collection('bookings'); bookings.doc(placeId).collection('bookings').withConverter<SportBooking>( fromFirestore: (snapshots, _) => SportBooking.fromJson(snapshots.data()!), toFirestore: (snapshots, _) => snapshots.toJson(), ).where('bookingStart', isGreaterThanOrEqualTo: startOfDay) .where('bookingStart', isLessThanOrEqualTo: endOfDay) .snapshots(),

is this code stored inside the ApiRepository.dart?

simonka0808 avatar Feb 11 '23 15:02 simonka0808

@simonka0808

In my case, I had this in my ApiRepository:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:sport.bp/app/data/sport_booking.dart';


class ApiRepostiory extends GetxService {
  static ApiRepostiory to = Get.find<ApiRepostiory>();

...
  CollectionReference bookings = FirebaseFirestore.instance.collection('bookings');

  Future<ApiRepostiory> init() async {
    return this;
  }

  CollectionReference<SportBooking> getBookingStream({required String placeId}) {
    return bookings.doc(placeId).collection('bookings').withConverter<SportBooking>(
          fromFirestore: (snapshots, _) => SportBooking.fromJson(snapshots.data()!),
          toFirestore: (snapshots, _) => snapshots.toJson(),
        );
  }
...
}

It looked like this, hope it helps, it was an old project, if I would have the time I would build a new fully Firebase compatible example with best practices, but I am pretty busy

radikris avatar Feb 14 '23 07:02 radikris