add method

Future add(
  1. Map<String, dynamic> data
)

Implementation

Future add(Map<String, dynamic> data) async {
  if(fields.where((element) => element.fieldtype == Dtype.autoIncrement).isNotEmpty){
    bool throwException = false;
    fields.where((element) => element.fieldtype == Dtype.autoIncrement).forEach((element) {
      if(!(element.field == 'id')){
        throwException = true;
      }else{
        throwException = false;
      }

    });
    if(throwException){
      throw Exception('id field must be autoIncrement and is required');
    }
  }else{
    throw Exception('id field must be autoIncrement and is required');
  }
  var dataSet = await _getAllDocs();
  if (dataSet.isNotEmpty) {
    Map<String, dynamic> doc = dataSet.first.data;
    if (fields.length != doc.length) {
      Map<String, dynamic> extra = {};
      fields
          .where((element) => !doc.containsKey(element.field))
          .forEach((item) {
        if (!doc.containsKey(item.field)) {
          extra.addAll({item.field: null});
        } else {
          extra.addAll({item.field: doc[item.field]});
        }
      });
      database().doc(doc['id'].toString()).update(extra);
    }
  }
  _doc.clear();
  for (var element in fields) {
    if (element.fieldtype == Dtype.autoIncrement) {
      _doc.addAll(
          {element.field: dataSet.isEmpty ? 1 : dataSet.last.data['id'] + 1});
    } else if (element.dataType == DatatypeEnum.model) {
      if (element.field == 'id') {
        throw Exception('id field must be autoIncrement');
      }
      try {
        var a =
            await FirebaseFirestore.instance.doc(data[element.field]).get();
        if (a.exists) {
          _doc.addAll({element.field: data[element.field]});
        } else {}
      } catch (e) {
        if (data[element.field] == null) {
          _doc.addAll({element.field: data[element.field]});
        } else {
          throw Exception(
              'Reference ${data[element.field]} not found in Model');
        }
      }
    } else if (data.containsKey(element.field)) {
      _doc.addAll({element.field: data[element.field]});
    } else {
      throw Exception('Field ${element.field} not found in data');
    }
  }

  database()
      .doc((dataSet.isEmpty ? 1 : dataSet.last.data['id'] + 1).toString())
      .set(_doc);

  firestore.collection('Xactivity').add({
    'activity': 'Added $className',
    'time': DateTime.now(),
    'by' : FirebaseAuth.instance.currentUser!.email,
  });
  _formValue.clear();
}