Boa tarde. Fazendo o teste de adicionar a mesma transação, não aparece o erro na tela que a transação já existe, apenas a mensagem de sucesso. No console apresenta a mensagem esperada em seguida de um erro:
I/flutter (8074): Response
I/flutter ( 8074): status code: 409
I/flutter ( 8074): headers: {content-type: text/plain;charset=UTF-8, date: Sun, 18 Jul 2021 19:18:06 GMT, content-length: 26}
I/flutter ( 8074): body: transaction already exists
E/flutter ( 8074): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 8074): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 8074): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
Segue o código:
class TransactionWebClient {
Future<List<Transaction>> findAll() async {
final http.Response response = await client
.get(Uri.parse(baseURL))
.timeout(const Duration(seconds: 5));
final List<dynamic> decodedJson = jsonDecode(response.body);
return decodedJson
.map((dynamic json) => Transaction.fromJson(json))
.toList();
}
Future<Transaction?> save(Transaction transaction, String password) async {
final String transactionJson = jsonEncode(transaction.toJson());
await Future.delayed(Duration(seconds: 10));
final http.Response response = await client
.post(
Uri.parse(baseURL),
headers: {"Content-type": "application/json", "password": password},
body: transactionJson,
)
.timeout(Duration(seconds: 5));
if (response.statusCode == 200) {
return Transaction.fromJson(jsonDecode(response.body));
}
throw HttpException(_getMessage(response.statusCode));
}
String? _getMessage(int statusCode) {
if (_statusCodeResponses.containsKey(statusCode)) {
return _statusCodeResponses[statusCode];
}
return "Unknown error";
}
static final Map<int, String> _statusCodeResponses = {
400: "there was an error submitting transaction",
401: "authentication failed",
409: "transaction already exists",
};
}
class HttpException implements Exception {
final String? message;
HttpException(this.message);
}