我正在使用flutter_bloc(https://felangel.github.io/bloc/#/gettingstarted)软件包,它真是太神奇了。当前,我有一个auth bloc,它在用户登录时保存访问 token 。

在我的许多HTTP请求中,我需要将访问 token 发送到后端。

我正在创建一个可重用的函数来处理所有需要发送访问 token 的 protected HTTP请求。这将是可重用的,因此我不必一直将访问 token 从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(
...

这是我用于 protected 请求的可重用功能。我需要在此功能中访问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();
    }
  }

谢谢

最佳答案

我可以为您提供一个dio(https://pub.dev/packages/dio)的软件包,它可以帮助您处理HTTP Requests。您可以使用该软件包创建一个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);
    }
  }
}

关于flutter - 我如何在我的API请求类(无部件类)中访问bloc,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58356131/

10-12 01:35