Estou fazendo o curso de Flutter: Streams de programação reativa com BLoC em 2021 e algumas bibliotecas mudaram, alterando alguns nomes de métodos, como por exemplo o "context.bloc()" que hoje temos que substituir para "context.read()". Para facilitar e agilizar o estudo de todos venho deixar os 3 scripts que sofrem com essas atualizações, vocês só precisam copiar estes scripts novos e substituir pelos antigos presentes nos projetos completos das aulas que baixamos através do github!
logging_interceptor.dart
import 'package:http_interceptor/http_interceptor.dart';
class LoggingInterceptor implements InterceptorContract {
@override
Future<RequestData> interceptRequest({RequestData data}) async {
print(data);
return data;
}
@override
Future<ResponseData> interceptResponse({ResponseData data}) async {
print(data);
return data;
}
}
transaction_web_client.dart
import 'dart:convert';
import 'package:bytebank/http/webclient.dart';
import 'package:bytebank/models/transaction.dart';
import 'package:http/http.dart';
class TransactionWebClient {
Future<List<Transaction>> findAll() async {
final Response response =
await client.get(baseUrl);
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: 2));
final Response response = await client.post(baseUrl,
headers: {
'Content-type': 'application/json',
'password': password,
},
body: transactionJson);
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);
}
webclient.dart
import 'package:http/http.dart';
import 'package:http_interceptor/http/http.dart';
import 'interceptors/logging_interceptor.dart';
final Client client = InterceptedClient.build(
interceptors: [LoggingInterceptor()],
requestTimeout: Duration(seconds: 5),
);
Uri baseUrl = Uri.parse('http://IP_DA_SUA_MAQUINA:8080/transactions');