How to save a field as 'null' to Firebase if no value is entered in TextFormField

Viewed 237

'?? null' works if only the first field has it, however it won't save if the other field(s) also has '?? null'. Is there a better way to write this?

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());
              
             

The Map in the models file

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

The integers are what are preventing the save. Instead of using int.parse, use int.tryParse.

Related