How to put this dart class together so I can use it in different parts of my code - flutter

I am trying to implement a Dio interceptor so I will be able to use it with my code.
I will be using this interceptor in many places. So I thought it would make sense to put it into a class or an interface whichever is best and just extend or implement it my subclasses.
I have this so far:
class AppInterceptor {
Dio dio = Dio();
AppInterceptor() {
dio.interceptors
.add(InterceptorsWrapper(onRequest: (Options options) async {
var token = await getAuthorizationToken();
options.headers["Authorization"] = 'Bearer $token';
return options;
}, onResponse: (Response response) {
// Finally, the string is parsed into a JSON object.
//print(response.toString());
return response;
}, onError: (DioError e) {
print('somthing went wrong');
// Do something with response error
return e; //continue
}));
}
}
How do I use this in a subclass to make an http call?
I tried something like this when trying to do my http call:
Response response = await AppInterceptor.dio.post(Global.functionsUrl+'/auth/linkuseraccount/', data: {'hey': 'hello'});
print(response);
It fails each time with Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [403]
From my backend, I can tell that it fails because the interceptor didn't pass in the authentication header.
How should I go about this?

Related

Dio Client: if request to protected route fails (401 code), then refresh the token and try again. Struggling to create

I am trying to create a custom ApiClient class that I can inject as a dependency (with get_it package) to be used in the data layer of my application. In order not to worry about access tokens throughout the presentation/application/domain layers of my app, I'd like to have a field, accessToken, that keeps track of the accessToken inside the ApiClient (singleton) class.
The ApiClient class would be used all throughout my data layer to handle requests to my server for data. It should have a method that allows me to add my own requests to it for unique routes. Then, if those routes require access tokens, it will add the accessToken field from the class along with the request. If that access token is invalid (expired/tampered with), then I would use the refresh token from the device's storage and send a request to the server to get a new access token, then try the original request again. It would "retry" the request at maximum once. Then, if there's still an error, it just returns that to be handled.
I am really struggling with how to implement this. My current attempt is below. Any help would be amazing!
class ApiClient {
final String baseUrl;
final Dio dio;
final NetworkInfo networkInfo;
final FlutterSecureStorage secureStorage;
ApiClient(
{required this.baseUrl,
required this.dio,
required this.networkInfo,
required this.secureStorage}) {
dio.interceptors.add(RefreshInvalidTokenInterceptor(networkInfo, dio, secureStorage));
}
}
class RefreshInvalidTokenInterceptor extends QueuedInterceptor {
final NetworkInfo networkInfo;
final Dio dio;
final FlutterSecureStorage secureStorage;
String? accessToken;
RefreshInvalidTokenInterceptor(this.networkInfo, this.dio, this.secureStorage);
#override
Future onError(DioError err, ErrorInterceptorHandler handler) async {
if (_shouldRetry(err) && await networkInfo.isConnected) {
try {
// access token request (using refresh token from flutter_secure_storage)
final refreshToken = await secureStorage.read(key: "refreshToken");
final response = await dio.post(
"$kDomain/api/user/token",
queryParameters: {"token": refreshToken},
);
accessToken = response.data["accessToken"];
return err;
} on DioError catch (e) {
handler.next(e);
} catch (e) {
handler.next(err);
}
} else {
handler.next(err);
}
}
bool _shouldRetry(DioError err) =>
(err.response!.statusCode == 403 || err.response!.statusCode == 401);
}
There are similar questions online, but none seem to answer my question! :)
EDIT: I've gotten a working solution (almost), with just 1 error. This works (except in the function retryRequest() I'm hardcoding the request to be a post request):
<imports removed for simplicity>
class ApiClient {
final Dio dio;
final NetworkInfo networkInfo;
final FlutterSecureStorage secureStorage;
String? accessToken;
ApiClient({
required this.dio,
required this.networkInfo,
required this.secureStorage,
}) {
dio.options = BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000,
receiveDataWhenStatusError: true,
followRedirects: true,
headers: {"content-Type": "application/json"},
);
dio.interceptors.add(QueuedInterceptorsWrapper(
//! ON REQUEST
onRequest: (options, handler) {
handler.next(options);
},
//! ON RESPONSE
onResponse: (response, handler) {
print("onResponse...");
handler.next(response);
},
//! ON ERROR
onError: (error, handler) async {
print("onError...");
if (tokenInvalid(error)) {
print("token invalid: retrying");
print("header before: ${dio.options.headers}");
await getAccessTokenAndSetToHeader(dio);
print("header after: ${dio.options.headers}");
final response = await retryRequest(error, handler);
handler.resolve(response);
print("here-1");
} else {
handler.reject(error);
}
print("here-2");
print("here-3");
},
));
}
Future<String?> getRefreshToken() async => await secureStorage.read(key: "refreshToken");
Future<void> getAccessTokenAndSetToHeader(Dio dio) async {
final refreshToken = await secureStorage.read(key: "refreshToken");
if (refreshToken == null || refreshToken.isEmpty) {
print("NO REFRESH TOKEN ERROR; LOGOUT!!!");
throw ServerException();
} else {
final response = await dio.post(
"$kDomain/api/user/token",
data: {"token": refreshToken},
);
dio.options.headers["authorization"] = "Bearer ${response.data["accessToken"]}";
}
}
// This function has the hardcoded post
Future<Response> retryRequest(DioError error, ErrorInterceptorHandler handler) async {
print("retry called, headers: ${dio.options.headers}");
final retryResponse = await dio.post(error.requestOptions.path);
print("retry results: $retryResponse");
return retryResponse;
}
bool tokenInvalid(DioError error) =>
error.response?.statusCode == 403 || error.response?.statusCode == 401;
Future<void> refreshToken() async {}
bool validStatusCode(Response response) =>
response.statusCode == 200 || response.statusCode == 201;
}
However, if I change the hardcoded post request to:
final retryResponse =
await dio.request(error.requestOptions.path, data: error.requestOptions.data);
the code no longer works... anyone know why? Having it dynamic based on whatever the failed request was, lets me re-use this class.
package:dio already include the BaseOptions which you can use to add some basic configuration like the baseUrl.
After that, you could use interceptors to add the accessToken to every request. To do this depending on your state management solution you can update the accessToken when the user authentication state changes.
And finally regarding the token refresh you can checkout package:fresh_dio.
Figured it out! (code + how to use below)
Here is my entire ApiClient class (imports hidden for simplicity). It acts as an HTTP client using dio:
class ApiClient {
final Dio dio;
final NetworkInfo networkInfo;
final FlutterSecureStorage secureStorage;
String? accessToken;
/// The base options for all requests with this Dio client.
final BaseOptions baseOptions = BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000,
receiveDataWhenStatusError: true,
followRedirects: true,
headers: {"content-Type": "application/json"},
baseUrl: kDomain, // Domain constant (base path).
);
/// Is the current access token valid? Checks if it's null, empty, or expired.
bool get validToken {
if (accessToken == null || accessToken!.isEmpty || Jwt.isExpired(accessToken!)) return false;
return true;
}
ApiClient({
required this.dio,
required this.networkInfo,
required this.secureStorage,
}) {
dio.options = baseOptions;
dio.interceptors.add(QueuedInterceptorsWrapper(
// Runs before a request happens. If there's no valid access token, it'll
// get a new one before running the request.
onRequest: (options, handler) async {
if (!validToken) {
await getAndSetAccessTokenVariable(dio);
}
setHeader(options);
handler.next(options);
},
// Runs on an error. If this error is a token error (401 or 403), then the access token
// is refreshed and the request is re-run.
onError: (error, handler) async {
if (tokenInvalidResponse(error)) {
await refreshAndRedoRequest(error, handler);
} else {
// Other error occurs (non-token issue).
handler.reject(error);
}
},
));
}
/// Sets the current [accessToken] to request header.
void setHeader(RequestOptions options) =>
options.headers["authorization"] = "Bearer $accessToken";
/// Refreshes access token, sets it to header, and resolves cloned request of the original.
Future<void> refreshAndRedoRequest(DioError error, ErrorInterceptorHandler handler) async {
await getAndSetAccessTokenVariable(dio);
setHeader(error.requestOptions);
handler.resolve(await dio.post(error.requestOptions.path,
data: error.requestOptions.data, options: Options(method: error.requestOptions.method)));
}
/// Gets new access token using the device's refresh token and sets it to [accessToken] class field.
///
/// If the refresh token from the device's storage is null or empty, an [EmptyTokenException] is thrown.
/// This should be handled with care. This means the user has somehow been logged out!
Future<void> getAndSetAccessTokenVariable(Dio dio) async {
final refreshToken = await secureStorage.read(key: "refreshToken");
if (refreshToken == null || refreshToken.isEmpty) {
// User is no longer logged in!
throw EmptyTokenException();
} else {
// New DIO instance so it doesn't get blocked by QueuedInterceptorsWrapper.
// Refreshes token from endpoint.
try {
final response = await Dio(baseOptions).post(
"/api/user/token",
data: {"token": refreshToken},
);
// If refresh fails, throw a custom exception.
if (!validStatusCode(response)) {
throw ServerException();
}
accessToken = response.data["accessToken"];
} on DioError catch (e) {
// Based on the different dio errors, throw custom exception classes.
switch (e.type) {
case DioErrorType.sendTimeout:
throw ConnectionException();
case DioErrorType.connectTimeout:
throw ConnectionException();
case DioErrorType.receiveTimeout:
throw ConnectionException();
case DioErrorType.response:
throw ServerException();
default:
throw ServerException();
}
}
}
}
bool tokenInvalidResponse(DioError error) =>
error.response?.statusCode == 403 || error.response?.statusCode == 401;
bool validStatusCode(Response response) =>
response.statusCode == 200 || response.statusCode == 201;
}
It should be injected as a singleton to your project so there's one instance of it (for the sake of keeping the state of its accessToken field). I used get_it like so:
// Registers the custom ApiClient class.
sl.registerLazySingleton(() => ApiClient(dio: sl(), networkInfo: sl(), secureStorage: sl()));
Then, inside your data layer (or wherever you call APIs from), you can use it by passing it through the constructor:
class MyDatasource implements IMyDatasource {
final ApiClient apiClient;
late Dio api;
FeedDatasource({required this.client, required this.apiClient}) {
api = apiClient.dio;
}
// Logic for your class here.
}
I simplified it to api so I wouldn't have to go apiClient.dio... every call (optional).
Then, you can use it in one of your class' methods like so:
#override
Future<List<SomeData>> fetchSomeDataFromApi() async {
try {
final response = await api.post("/api/data/whatYouWant");
throw ServerException();
} catch (e) {
throw ServerException();
}
}
Now, for this request, if your class has a valid access token (non-null, non-empty, non-expired), it will call normally. However, if your token isn't valid, it'll refresh it first, then proceed with your call. Even if the call fails after the token originally passed the validation check (token somehow expires during the call for example), it will still be refreshed, and the call re-executed.
Note: I use a lot of custom exceptions, this is optional.
Hopefully this helps someone else!

Connection closed before full header was received http post in flutter

I'm having problems trying to consume my API, and after following up on this problem I'm stuck in the matter and I've tried different emulators in various versions and the problem persists.
Error:
DioError [DioErrorType.other]: HttpException: Connection closed before full header was received, uri = http://10.0.2.2:7108/Users/authenticate
Flutter doctor
Http Post
class AuthenticateRemoteApi extends AuthenticateGateway {
final AuthenticateMapper _authenticateMapper = AuthenticateMapper();
#override
Future<SesionUser> login(Authenticate user) async {
var dio = Dio();
dio.options.headers['content-Type'] = 'application/json';
String url = 'http://10.0.2.2:7108/Users/authenticate';
try {
Response response = await dio.post(url, data: authenticateModelToJson(user));
return _authenticateMapper.fromMap(jsonDecode(response.data));
} catch (e) {
throw Exception(e);
}
}
}
I have came with this work around by creating this interceptor.
The idea of it is when encountering this random error just to retry the request.
/// Interceptor
class RetryOnConnectionChangeInterceptor extends Interceptor {
final Dio dio;
RetryOnConnectionChangeInterceptor({
required this.dio,
});
#override
void onError(DioError err, ErrorInterceptorHandler handler) async {
if (_shouldRetryOnHttpException(err)) {
try {
handler.resolve(await DioHttpRequestRetrier(dio: dio).requestRetry(err.requestOptions).catchError((e) {
handler.next(err);
}));
} catch (e) {
handler.next(err);
}
} else {
handler.next(err);
}
}
bool _shouldRetryOnHttpException(DioError err) {
return err.type == DioErrorType.other &&
((err.error is HttpException && err.message.contains('Connection closed before full header was received')));
}
}
/// Retrier
class DioHttpRequestRetrier {
final Dio dio;
DioHttpRequestRetrier({
required this.dio,
});
Future<Response> requestRetry(RequestOptions requestOptions) async {
return dio.request(
requestOptions.path,
cancelToken: requestOptions.cancelToken,
data: requestOptions.data,
onReceiveProgress: requestOptions.onReceiveProgress,
onSendProgress: requestOptions.onSendProgress,
queryParameters: requestOptions.queryParameters,
options: Options(
contentType: requestOptions.contentType,
headers: requestOptions.headers,
sendTimeout: requestOptions.sendTimeout,
receiveTimeout: requestOptions.receiveTimeout,
extra: requestOptions.extra,
followRedirects: requestOptions.followRedirects,
listFormat: requestOptions.listFormat,
maxRedirects: requestOptions.maxRedirects,
method: requestOptions.method,
receiveDataWhenStatusError: requestOptions.receiveDataWhenStatusError,
requestEncoder: requestOptions.requestEncoder,
responseDecoder: requestOptions.responseDecoder,
responseType: requestOptions.responseType,
validateStatus: requestOptions.validateStatus,
),
);
}
}
Usage: add this interceptor [RetryOnConnectionChangeInterceptor] to your Dio client instance
I think this could be a package bug, usually appears when the user doesn't has internet connect. Reported in #1269 and #377 issue from the package repository. I recommend you to use another package.
In my case this error always occurs when I build app on emulator, rarely appears on real device. If you are using Android Studio, try with Pixel 6 API 33.

Dio Cancel current running API before starting a new API request

I am using DIO package for API request but the issue is that when I request for another API while the first API is still in progress.
It doesn't cancel the first request. Both the APIs run simultaneously which is not the desired in my app scenario.
class DioClient {
static BaseOptions options = BaseOptions(baseUrl: baseUrl);
Dio _dio = Dio(options);
Future<dynamic> postFormData(
{dynamic data, String url, dynamic header}) async {
final data1 = data;
var formData = FormData.fromMap(data1);
try {
var response = await _dio.post(url,
options: Options(headers: header), data: formData);
return response.data;
} catch (e) {
throw e;
}}}
If you want to cancel the API request call then you need to use the cancel token provided by DIO.
You need to pass cancel token in dio request when you make other API call use that cancel token to cancel the API request
Here is the code
class DioClient {
static BaseOptions options = BaseOptions(baseUrl: baseUrl);
//Here is line you need
CancelToken cancelToken=CancelToken();
Dio _dio = Dio(options);
Future<dynamic> postFormData(
{dynamic data, String url, dynamic header}) async {
final data1 = data;
var formData = FormData.fromMap(data1);
try {
//pass cancel token here
var response = await _dio.post(url,
options: Options(headers: header), data: formData,cancelToken: cancelToken);
return response.data;
} catch (e) {
throw e;
}}}
And use that cancelToken to cancel the API request when you call another API first you cancel the previous request.
cancelToken.cancel();
Enjoy!

Dio instance doesnt return a response when getting a API endpoint

I am trying to get a response from an Api but there is no response in return.
Dio instance doesnt return a response when getting a API endpoint
import 'package:dio/dio.dart';
class DioService {
static const baseUrl = "https://dictionaryapi.dev/";
Dio dio = Dio();
DioService() {
initializeInterceptors();
}
initializeInterceptors() {
dio.interceptors.add(InterceptorsWrapper(onError: (e, _) {
print(e.message);
}, onRequest: (r, _) {
print(r.method);
print(r.path);
}, onResponse: (r, _) {
print(r.data);
}));
}
Future<Response> getRequest(String endPoint) async {
Response response;
try {
response = await dio.get(endPoint);
print(response.toString());
} on DioError catch (e) {
print(e);
throw Exception(e.message);
}
return response;
}
}
console :
I/flutter (17735): GET
I/flutter (17735): https://api.dictionaryapi.dev/api/v2/entries/en_US/dog
Your interceptor is routing the request into a black hole.
The second parameter to each interceptor method is a handler. In order to continue a request, the interceptor must pass (possibly modified) request options to the handler, and the same holds for the error and response handlers.
dio.interceptors.add(InterceptorsWrapper(onError: (e, handler) {
print(e.message);
handler.next(e);
}, onRequest: (r, handler) {
print(r.method);
print(r.path);
handler.next(r);
}, onResponse: (r, handler) {
print(r.data);
handler.next(r);
}));
For logging in particular, note that Dio provides a LogInterceptor class, so you don't need to roll your own.

rxDart not calling onError

I am trying to make a simple request to backend using rxDart. But the problem I face is that when I get a http error such as 404, onError is not called, however, it is possible to extract it in onData.
I have a little experience with RxJava + retrofit and there it works as expected, when there is a response with error http status code onError is called and can be handled appropriately.
1. What am I doing wrong, or is it intended behavior?.
Object sendProfileData() {
Stream<Response> stream = onboardingRepository.createUser(User(name: 'name', surname: 'surname', lat: 1.0, lng: 2.0));
stream.listen((response) {
print(response.statusCode);
setAttributes();
}, onError: (e) {
print(e);
});
}
OnboardingRepository.dart:
class OnboardingRepository {
Observable<Response> createUser(User user) {
return Observable.fromFuture(TMApi.createUser(user));
}
}
TMApi.dart:
class TMApi {
static Future<http.Response> createUser(User user) async {
String url = '$baseUrl/create_user';
return await http.post(url, body: json.encode(user.toJson()));
}
}
What would be the best way to handle the event in the View? There should be an error displayed if error occurs, otherwise it should open a new screen. sendProfileData() method will return an Object, based on that I am going to perform actions in the view, but that doesn't sound like a very elegant solution...
Any suggestions on architecture are welcome :)
the http library in dart works a bit different than Retrofit.
The Future returned by http.post only throws an exception when there is an io error (socket error, no internet).
Server responses like 404 are reflected in the http.Response.
I created a simple convenience method that might help you:
void throwIfNoSuccess(http.Response response) {
if(response.statusCode < 200 || response.statusCode > 299) {
print('http error!');
print(response.body);
throw new HttpException(response);
}
}
class HttpException implements Exception {
HttpException(this.response);
http.Response response;
}
How to use:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<UserProfile> getUserProfile(String userId) async {
final url = 'https://example.com/api/users/$userId';
final response = await http.get(url);
throwIfNoSuccess(response);
final jsonBody = json.decode(response.body);
return UserProfile.fromJson(jsonBody);
}