You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用Dio获取数据时出现间歇性FormatException问题

Flutter中使用Dio调用API间歇性出现FormatException:Unexpected end of input

在Flutter应用中使用Dio库从API获取数据时,遇到间歇性的FormatException,错误信息为**"Unexpected end of input"**。该异常并非持续出现,有时能正常获取数据,有时会触发此错误。

错误日志

DioException (DioException [unknown]: null
Error: FormatException: Unexpected end of input (at character 3247)
...2024-05-06T15:00:41.000000Z","updated_at":"2024-05-07T08:51:56.000000Z"}}}])

仓库代码

Future<ApiResult<AppointmentsResponse>> getAppointments() async {
  final dio = Dio();

  dio.interceptors.add(LogInterceptor(responseBody: true));
  dio.interceptors.add(LogInterceptor(requestBody: true));

  try {
    final prefs = await SharedPreferences.getInstance();
    final String? stored_token = await prefs.getString('token');
    final int? tech_id = await prefs.getInt('tech_id');

    final dio = DioFactory.getDio();

    final response = await dio.get(
        '$baseurl/api/appointments/tech/$tech_id/all',
        options: Options(
          headers: {'Authorization': 'Bearer $stored_token'},
        ));

    debugPrint("Raw API Response: $response");

    debugPrint('Response: ${response.statusCode}');
    debugPrint("response11: ${response.data}");

    // 处理响应数据
    Map<String, dynamic> responseData = response.data is Map<String, dynamic>
        ? response.data
        : jsonDecode(response.data);
    return ApiResult.success(AppointmentsResponse.fromJson(responseData));
  } catch (e, stacktrace) {
    logger.e("Error: $e, StackTrace: $stacktrace");
    return ApiResult.failure(e.toString());
  }
}

Bloc Provider代码

BlocProvider<AppointmentCubit>(
        create: (BuildContext context) => AppointmentCubit(AppointmentRepo(
            apiService: ApiService(Dio(BaseOptions(
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          },
          followRedirects: false,
          // 不会抛出状态码错误
          validateStatus: (status) => true,
        ))))),
      ),

内容的提问来源于stack exchange,提问作者Mahmoud Shaaban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:07:31