toString method
A string representation of this object.
Some classes have a default textual representation,
often paired with a static parse function (like int.parse).
These classes will provide the textual representation as
their string representation.
Other classes have no meaningful textual representation
that a program will care about.
Such classes will typically override toString to provide
useful information when inspecting the object,
mainly for debugging or logging.
Implementation
@override
String toString() {
DateFormat dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
DateTime start = this.start ?? DateTime.now();
DateTime end = this.end ?? DateTime.now();
final String startTimeFormatted = dateFormat.format(start);
final String endTimeFormatted = dateFormat.format(end);
final int duration = end.difference(start).inMilliseconds;
String requestBody;
try {
if (request?.data == null) {
requestBody = 'null';
} else if (request?.data is String) {
requestBody = request?.data as String;
} else {
requestBody = jsonEncode(request?.data);
}
} catch (e) {
requestBody = request?.data.toString() ?? 'null';
}
String responseBody;
try {
if (response?.data == null) {
responseBody = 'null';
} else if (response?.data is String) {
responseBody = response?.data as String;
} else {
responseBody = jsonEncode(response?.data);
}
} catch (e) {
responseBody = response?.data.toString() ?? 'null';
}
String headersString;
try {
headersString = jsonEncode(request?.headers);
} catch (e) {
headersString = request?.headers.toString() ?? 'null';
}
String logAPI =
'''\n
$startTimeFormatted: Request API
URL: ${request?.baseUrl}${request?.path}
Method: ${request?.method}
Headers: $headersString
Body: $requestBody
Start Time: $startTimeFormatted
End Time: $endTimeFormatted
Duration: $duration ms
Response Code: ${response?.statusCode ?? -1}
Response Message: ${response?.statusMessage ?? error?.message ?? 'No message'}
Response Body: $responseBody
''';
return logAPI;
}