MST

星途 面试题库

面试题:Flutter异步/await网络请求的异常处理与稳定性提升

假设你在Flutter应用中使用异步/await进行网络请求,在网络不稳定的情况下,可能会出现多种异常,如超时、连接失败等。请阐述你会如何全面地处理这些异常,以提升网络请求的稳定性,并给出具体代码示例,包括如何设置超时时间以及处理不同类型异常的方式。
47.5万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

在Flutter应用中使用异步/await进行网络请求时,为了全面处理网络不稳定情况下的异常,提升网络请求的稳定性,可以按照以下方式:

  1. 设置超时时间:在http请求中,可以使用Duration来设置超时时间。
  2. 处理不同类型异常:主要处理SocketException(连接失败)、TimeoutException(超时)以及其他未处理的Exception

以下是具体代码示例:

import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'dart:async';

Future<String> fetchData() async {
  try {
    final response = await http.get(
      Uri.parse('https://example.com/api/data'),
      // 设置超时时间为5秒
      timeout: const Duration(seconds: 5),
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('Failed to load data, status code: ${response.statusCode}');
    }
  } on SocketException {
    throw Exception('Failed to connect to the server');
  } on TimeoutException {
    throw Exception('Request timed out');
  } catch (e) {
    throw Exception('An error occurred: $e');
  }
}

在上述代码中:

  • 使用http.get发起网络请求,并通过timeout参数设置了5秒的超时时间。
  • 使用try-catch块捕获异常,针对SocketExceptionTimeoutException分别进行处理,同时也有一个通用的catch块来捕获其他可能出现的异常。这样可以有效地处理各种网络异常,提升网络请求的稳定性。