I'm using the flutter_bloc (https://felangel.github.io/bloc/#/gettingstarted) package which has been amazing. Currently, I have an auth bloc which holds an access token when the user is logged in.
On many of my HTTP requests, I need to send the access token to my back-end.
I am creating a re-usable function to handle all protected HTTP requests that require an access token to be sent. This will be reusable so I don't have to keep passing the access token from my UI layer to my API layer. However, I'm not sure how to access the Auth Bloc from this function since it is not in the widget tree
Data flows like so when I make an HTTP request (based on felangel's flutter bloc tutorials):
UI -> bloc -> repository -> api
and then:
api -> repository -> bloc -> UI
I have a BlocProvider near the top of my app to provide the AuthBloc, like so:
return BlocProvider(
builder: (BuildContext context) =>
AuthBloc(authRepository: authRepository),
child: Scaffold(
...
And here is my re-usable function for protected requests. I need to access the Auth Bloc in this function, but I'm not entirely sure how to.
Future<dynamic> protectedRequest(
{accessToken, endpoint, dynamic body}) async {
final uri = Uri.https(baseUrl, endpoint);
final response = await http.post(uri,
body: body, headers: {'Authorization': 'Bearer ' + accessToken});
if (response.statusCode == 200 || response.statusCode == 201) {
return response;
} else {
throw Exception();
}
}
Thank You