ashf
ashf

Reputation: 217

How to not save a field to Fireabse if left empty

I have a page with TextFormFields - how do I NOT save a field to Firebase if the user leaves it empty? I'm guessing if statements with .isEmpty, but I'm not sure where to implement them:

onPressed: () async {
          final uid =
              await TheProvider.of(context).auth.getCurrentUID();

          //save data to firebase

          widget.contact.name = oneController.text;
          widget.contact.phoneNumber = int.parse(twoController.text);
          widget.contact.location = threeController.text;
          widget.contact.rating = int.parse(fourController.text);
          widget.contact.instagram = fiveController.text;
          widget.contact.birthday = int.parse(sixController.text);
          widget.contact.notes = sevenController.text;

          await db
              .collection("userData")
              .doc(uid)
              .collection("Contacts")
              .add(widget.contact.toJson());

Models file

class Contact {
int rating;
String name;
String location;
int phoneNumber;
String instagram;
int birthday;
String notes;


Contact(this.name, this.phoneNumber, this.location, this.rating,
        this.instagram, this.birthday, this.notes);


Map<String, dynamic> toJson() => {
    'Name': name,
    'PhoneNumber': phoneNumber,
    'Location': location,
    'Rating': rating,
    'Instagram': instagram,
    'Birthday': birthday,
    'Notes': notes,
    
  };
}

An example of one of the TextFormFields

TextFormField(
                controller: fourController,
                style: TextStyle(color: Colors.tealAccent),
                cursorColor: Colors.white,
                decoration:
                    textInputDecoration.copyWith(hintText: 'Rating'),
                keyboardType: TextInputType.number),

Upvotes: 0

Views: 345

Answers (2)

ashf
ashf

Reputation: 217

int.tryParse when intialising text editing controllers instead of int.parse (for integer TextFormFields).

Upvotes: 0

August Kimo
August Kimo

Reputation: 1771

Usually if I have/might have empty fields for info a user doesn't set I just upload it as null, and when displaying/using the info I handle the null values. (Don't display birthday if(birthday==null)).

If you don't want to do that, how about you first create a map in the Contact class, and remove the empty values from the map before turning the map to JSON? I think this would be easiest.

Here is how to remove values from a map in dart:

Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'};
map.remove(2); //enter the key you wish to remove

Combine that with if statements checking if every value is null, and removing it from the map if it is.

Upvotes: 1

Related Questions