【问题标题】:Flutter http.post method doesn't work for me. Every time I try to run it, it brings up ticker.dartFlutter http.post 方法对我不起作用。每次我尝试运行它时,它都会弹出ticker.dart
【发布时间】:2021-02-25 00:05:09
【问题描述】:
Future<LoginResponse> authenticate(LoginRequest request) async {
  var url = _baseUrl + loginUrl;
  Map<String, String> headers = {'Content-Type': 'application/json;'};
  final res = await http.post(url, headers: headers, body: request.toJson());
  if (res.statusCode == 201) {
    Map<String, dynamic> response = jsonDecode(res.body);
    var json = LoginResponse(res.statusCode,
        response: response, token: response['user_access_token']['key']);
    return json;
  } else {
    Map<String, dynamic> response = jsonDecode(res.body);
    var json =
        LoginResponse(res.statusCode, response: response, error: res.body);
    return json;
  }
}

这是我在 UserRepository 中的代码,我正在使用 flutter_bloc 传入请求模型。

下面是 AuthBloc 中的逻辑。我很确定问题出在http.post 方法中,因为当我删除标头时,我的请求已被处理但响应错误。

Stream<AuthState> _mapLoginToState(String email, String password) async* {
  yield AuthenticationLoadingState();
  LoginRequest request =
      LoginRequest(email: email, password: password);
  var res = await userRepository.authenticate(request);
  if (res.code == 201) {
    var token = res.token;
    if (token != '' && token != null) {
      await userRepository.saveToken(token);
      yield AuthenticatedState();
    } else {
      await userRepository.deleteToken();
      yield UnAuthenticatedState();
    }
  } else {
    print(res.error);
  }
}

【问题讨论】:

    标签: flutter http flutter-bloc


    【解决方案1】:

    我想通了。问题是我忘记将jsonEncode() 包裹在正文上。

    我解决了问题,代码正常工作。

    【讨论】:

      猜你喜欢
      • 2023-01-08
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多