Hamza
Hamza

Reputation: 2045

How to skip null/empty variables in the firestore collection?

Like firebase real-time database, I don't want store null/empty value in firestore collection .so how i can skip or remove null fields from firestore collection enter image description here

below function save data to firestore

private void saveTofireStore(String path, User userObject,Class<?> classType){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    documentReference = db.document(path);
    Log.d(TAG,""+documentReference.getPath());
   documentReference
            .set(userObject)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()){
                  appearanceMutableLiveData.setValue(task.getResult());
                }else {
                    appearanceMutableLiveData.setValue(null);
                }
            });

}

Upvotes: 7

Views: 3780

Answers (2)

Hamza
Hamza

Reputation: 2045

I found an easy way using Gson to serialize object then convert into the map then you can save that object

private Map<String, Object> removeNullValues(User userObject) {
    Gson gson = new GsonBuilder().create();

    Map<String, Object> map = new Gson().fromJson(
            gson.toJson(userObject), new TypeToken<HashMap<String, Object>>() {
            }.getType()
    );

    return map;
}

and then

documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}

If you are using proguard then make sure add this rules

-keepclassmembers enum * { *; }

Upvotes: 9

teteArg
teteArg

Reputation: 4024

My solution was to add a method called toFirestoreJson.

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  String documentID;
  final String name;
  final String city;
  final String postalCode;
  final String state;
  final String address;
  final List<String> emails;

  User(
      {this.name,
      this.city,
      this.postalCode,
      this.state,
      this.address,
      this.emails});

  factory User.fromFirestore(DocumentSnapshot documentSnapshot) {
    User data = User.fromJson(documentSnapshot.data);
    data.documentID = documentSnapshot.documentID;
    return data;
  }

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"] == null ? null : json["name"],
        city: json["city"] == null ? null : json["city"],
        postalCode: json["postal_code"] == null ? null : json["postal_code"],
        state: json["state"] == null ? null : json["state"],
        address: json["address"] == null ? null : json["address"],
        emails: json["emails"] == null
            ? null
            : List.castFrom(json["emails"]),
      );

  Map<String, dynamic> toFirestoreJson() {
    Map json = toJson();
    json.removeWhere((key, value) => value == null);
    return json;
  }

  Map<String, dynamic> toJson() => {
        "name": name == null ? null : name,
        "city": city == null ? null : city,
        "postal_code": postalCode == null ? null : postalCode,
        "state": state == null ? null : state,
        "address": address == null ? null : address,
        "emails" : emails == null ? null : emails,
      };
}

Upvotes: 1

Related Questions