hukusuke1007 / flamingo

[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤
https://pub.dev/packages/flamingo
MIT License
118 stars 20 forks source link

Add Support for Fields which cannot be null #34

Open vladaman opened 3 years ago

vladaman commented 3 years ago

We have following field which has no value in Firestore. If we fetch this model we get an error. We do not want to add bool? since we take this value as default if it's not present.

// Field Definition
@Field()
bool requireSomeField = false;
2021-07-28 11:09:24.547 25564-25650/eu.app E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'Null' is not a subtype of type 'bool' in type cast
    #0      Helper.valueFromKey (package:flamingo/src/helper/helper.dart:214:18)
hukusuke1007 commented 3 years ago

@vladaman Please show me your source code.

dmba commented 3 years ago

@hukusuke1007 I am facing similar issue, it would be nice if the package would be able to support something like this (please pay attention on bool onBoardingCompleted = false; field):

class ProfileModel extends Document<ProfileModel> {
  ProfileModel({
    String? id,
    DocumentSnapshot<Json>? snap,
    Json? values,
  }) : super(
          id: id,
          snapshot: snap,
          values: values,
          collectionPath: 'profile',
        );

  @Field()
  bool onBoardingCompleted = false;

  @Field()
  String? firstName;

  @Field()
  String? lastName;

  @override
  Json toData() => _$toData(this);

  @override
  void fromData(Json data) => _$fromData(this, data);
}

Right not it generates code that cannot be compiled - defaultValue: null, it should be defaultValue: false:

/// For load data
void _$fromData(ProfileModel doc, Map<String, dynamic> data) {
  doc.onBoardingCompleted = Helper.valueFromKey<bool>(
      data, 'onBoardingCompleted',
      defaultValue: null);
  doc.firstName =
      Helper.valueFromKey<String?>(data, 'firstName', defaultValue: null);
  doc.lastName =
      Helper.valueFromKey<String?>(data, 'lastName', defaultValue: null);
}
hukusuke1007 commented 3 years ago

@dmba I'm consider new solution. Tentatively, please set nullable type like this.

@Field()
bool? onBoardingCompleted = false;

I'll suggest new solution in near future.

vladaman commented 3 years ago

@dmba I'm consider new solution. Tentatively, please set nullable type like this.

@Field()
bool? onBoardingCompleted = false;

I'll suggest new solution in near future.

Unfortunately this may work "technically" but IDE tooling suggests you have not handled null condition on these fields. IDE is not aware that this may not hold null value.