setData method

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

Writes to the document referred to by this DocumentReference.

If the document does not yet exist, it will be created. If the collection does not yet exist, it will be created. Returns a DocumentSnapshot with the ID generated at the server side.

Implementation

Future<DocumentSnapshot> setData(Map<String, dynamic> data) async {
  // Remember that the CARP collection service generated the ID and returns it in a POST.

  // If this document does not already exist on the server (i.e., have an ID), then create it
  if (id == null) {
    http.Response response = await httpr.post(Uri.encodeFull(documentUri),
        headers: headers, body: json.encode(data));
    int httpStatusCode = response.statusCode;
    Map<String, dynamic> responseJson =
        json.decode(response.body) as Map<String, dynamic>;

    if ((httpStatusCode == HttpStatus.ok) ||
        (httpStatusCode == HttpStatus.created)) {
      return DocumentSnapshot._(path, responseJson);
    }

    // All other cases are treated as an error.
    throw CarpServiceException(
      httpStatus: HTTPStatus(httpStatusCode, response.reasonPhrase),
      message: responseJson["message"].toString(),
      path: responseJson["path"].toString(),
    );
  } else {
    return updateData(data);
  }
}