Home > Mobile >  client.post login timeout not working in flutter
client.post login timeout not working in flutter

Time:08-19

I need to use timeout if post request not working so, I write below code:

class APIService {
  static var client = http.Client();
  static Future<bool> login(LoginRequestModel model) async {
    Map<String, String> requestHeaders = {
      'Content-Type': 'application/json',
    };
    var url = Uri.http(Config.apiURL, Config.loginAPI);
    try {
      final response = await client
          .post(
            url,
            headers: requestHeaders,
            body: jsonEncode(model.toJson()),
          )
          .timeout(const Duration(seconds: 5));
      print("response:");
      print(response);
      if (response.statusCode == 200) {
        //SHARED
        await SharedService.setLoginDetails(loginResponseJson(response.body));
        return true;
      } else {
        return false;
      }
    } on TimeoutException catch (e) {
      // handle timeout
      return false;
    }
  }

But never end await client.post method waiting althouth I add timeout. How can I solve this ?

CodePudding user response:

You can try this:

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

final body = { 'email': email, 'password': password };
  final client = http.Client();
  http.Response res;
  try {
    res = await client
      .post(
        url,
        headers: requestHeaders,
        body: jsonEncode(model.toJson()),
      .catchError((e) {
        // SocketException would show up here, potentially after the timeout.
      })
      .timeout(const Duration(seconds: 5));
  } on TimeoutException catch (e) {
    // Display an alert, no internet
  } catch (err) {
    print(err);
    return null;
  }
  • Related