我正在使用flutter_bloc(https://felangel.github.io/bloc/#/gettingstarted)软件包,这真了不起。当前,我有一个auth bloc,它在用户登录时保存访问令牌。
在我的许多HTTP请求中,我需要将访问令牌发送到后端。
我正在创建一个可重用的函数来处理所有需要发送访问令牌的受保护HTTP请求。这将是可重用的,因此我不必一直将访问令牌从UI层传递到API层。但是,我不确定如何从此函数访问Auth Bloc,因为它不在小部件树中
当我发出HTTP请求时数据流是这样的(基于felangel的flutter bloc教程):
UI -> bloc -> repository -> api
and then:
api -> repository -> bloc -> UI
我的应用程序顶部附近有一个BlocProvider,以提供AuthBloc,就像这样:
return BlocProvider(
builder: (BuildContext context) =>
AuthBloc(authRepository: authRepository),
child: Scaffold(
...
这是我对受保护请求的可重用功能。我需要在此功能中访问Auth Bloc,但是我不确定如何操作。
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();
}
}
谢谢
答案 0 :(得分:1)
我可以为您提供一个dio({https://pub.dev/packages/dio)的软件包,它可以在HTTP请求时为您提供帮助。您可以使用该软件包创建一个http管理器。
class HttpManager {
static String token;
static String cookie;
final String tag;
var _dio = Dio();
HttpManager({this.tag}) {
_dio.options..baseUrl = AppConfig.baseUrl;
_dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
if (token != null) {
options.headers["Authorization"] = "Bearer $token";
options.headers["cookie"] = cookie;
}
DioLogger.onSend(tag, options);
return options;
}, onResponse: (Response response) {
DioLogger.onSuccess(tag, response);
return response;
}, onError: (DioError error) {
if (error.response.statusCode == 401) {
AuthenticationBloc().logout();
} else if (error.response.statusCode == 400) {
error.response.statusMessage = "400";
}
DioLogger.onError(tag, error);
return error;
}));
}
Dio get client => _dio;
}
并且可以在您的身份验证服务中使用_dio变量,例如:
class AuthService {
final String tag = "AuthService";
Dio client;
AuthService() {
client = HttpManager(tag: tag).client;
}
Future<ResponseModel> authenticate(String username, String password) async {
try {
final response = await client.get("/myPath",
queryParameters: {"username": username, "password": password});
throwIfNoSuccess(response);
HttpManager.token = response.data["token"];
HttpManager.cookie = response.headers.value("cookie");
return ResponseModel.fromJson(response.data);
} catch (e) {
throw (e);
}
}
void throwIfNoSuccess(Response response) {
print("is the response Null : ${response.statusCode}");
if ((response.statusCode ?? 0) < 200 || (response.statusCode ?? 0) > 299) {
throw new HttpException(response);
}
}
}