save<T> method
Saves a CoffeeModel instance to the API.
Sends a POST or PUT HTTP request to save the provided json object to the API.
The HTTP method used (POST or PUT) is determined based on the usePutWhenId parameter
and whether json has a non-null id property.
Parameters:
endpoint: The API endpoint to send the request to.json: The object to save.isFormData: Optional. Whether to sendjsonas form data. Defaults tofalse.
If isFormData is true, json is converted to form data before being sent in the request.
If json is a CoffeeModel instance, it is converted to JSON using its toJson method.
Otherwise, json is sent as-is in the request.
Returns:
A SaveResponse instance that provides two methods:
- SaveResponse.useHttpPutWhenId: A function that sends the request using HTTP PUT if
json.idis non-null and greater than 0, and HTTP POST otherwise. SaveResponse.useHttpPost: A function that sends the request using HTTP POST.
Example:
save('/api_endpoint', model.toJson(), (json) => CoffeeModel.fromJson(json))
.useHttpPutWhenId().then((savedModel) {
print('Saved model: $savedModel');
});
OR
save('/api_endpoint', model.toJson(), (json) => CoffeeModel.fromJson(json))
.then((savedModel) {
print('Saved model: $savedModel');
});
Implementation
SaveResponse<T> save<T>({
required String endpoint,
required Map<String, dynamic> json,
required T Function(Map<String, dynamic>) fromJson,
bool isFormData = false
}) {
return SaveResponse<T>(
useHttpPutWhenId: () async {
final response = await update(endpoint, json, isFormData);
return fromJson(response) as T;
},
then: (dynamic Function(T) onData, {Function? onError}) async {
final response = await create(endpoint, json, isFormData);
final result = fromJson(response) as T;
onData(result);
return result;
},
);
}