Open tariqul000 opened 2 years ago
Eu criei essa classe para me atender nisso
`
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
class Api{
static const urlPrefix = 'http://xx.xx.xx.xx:port/router';
final resultNotifier = ValueNotifier<RequestState>(RequestInitial());
Future<dynamic> makeGetRequest(String router) async {
resultNotifier.value = RequestLoadInProgress();
final headers = {"Content-type": "application/json",
"Authorization": "bearer"};
final url = Uri.parse('$urlPrefix/$router');
Response response = await get(url, headers: headers);
print('Status code: ${response.statusCode}');
return _handleResponse(response);
}
Future<dynamic> makePostRequest(String router, String body) async {
resultNotifier.value = RequestLoadInProgress();
final url = Uri.parse('$urlPrefix/$router');
final headers = {"Content-type": "application/json",
"Authorization": "bearer"};
final response = await post(url, headers: headers, body: body);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
return _handleResponse(response);
}
Future<void> makePutRequest() async {
resultNotifier.value = RequestLoadInProgress();
final url = Uri.parse('$urlPrefix/posts/1');
final headers = {"Content-type": "application/json"};
final json = '{"title": "Hello", "body": "body text", "userId": 1}';
final response = await put(url, headers: headers, body: json);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
_handleResponse(response);
}
Future<void> makePatchRequest() async {
resultNotifier.value = RequestLoadInProgress();
final url = Uri.parse('$urlPrefix/posts/1');
final headers = {"Content-type": "application/json"};
final json = '{"title": "Hello"}';
final response = await patch(url, headers: headers, body: json);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
_handleResponse(response);
}
Future<void> makeDeleteRequest() async {
resultNotifier.value = RequestLoadInProgress();
final url = Uri.parse('$urlPrefix/posts/1');
final response = await delete(url);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
_handleResponse(response);
}
dynamic _handleResponse(Response response){
if (response.statusCode >= 400) {
return [{}] ;
} else {
return json.decode( response.body );
}
}
}
class RequestState {
const RequestState();
}
class RequestInitial extends RequestState {}
class RequestLoadInProgress extends RequestState {}
class RequestLoadSuccess extends RequestState {
const RequestLoadSuccess(this.body);
final String body;
}
class RequestLoadFailure extends RequestState {}
`
Suppose I have an attendance app where the user can give attendance with the face but someone can take her picture and give attendance every time, without being present there.