API call terminate when screen gets off (or app goes background) IOS Flutter

961 Views Asked by At

I have a login page which starts downloading base data for the app after user enters username and password, and its a long duration operation like 2 or 3 minutes

In IOS at the middle of downloading data if screen gets off and locked, the operations terminates.

Here is the code LoginPage part:

var repository = GlobalRestRepository();
var db = BasicDB();
List<basicModel> notDownloaded = await db.selectByLoaded(false);
for (int i = 0; i < notDownloaded.length; i++) {
    await repository.getBasic(notDownloaded.elementAt(i));
}

GlobalRestRepository part:

class GlobalRestRepository {
  final HttpClient http = HttpClient();

Future<void> getBasic(basicModel model) async {
    String url = "${Variables.mainUrl + basicModelUrl}";

    var response = await http.postExtraToken(url);
    .
    .
    .
 }
}

HttpClient part:

import 'package:http/http.dart';
...
class HttpClient {

  static final HttpClient _instance = HttpClient._privateConstructor();

  factory HttpClient() {
    return _instance;
  }

  Future<dynamic> postExtraToken(String path) async {
    Response response;
    try {
      response = await post(Uri.parse(path),
              headers: {"extra": Variables.extra, "token": Variables.token});
      final statusCode = response.statusCode;
      if (statusCode >= 200 && statusCode < 299) {
        if (response.body.isEmpty) {
          return [];
        } else {
          return jsonDecode(utf8.decode(response.bodyBytes));
        }
      } else if (statusCode >= 400 && statusCode < 500) {
        throw ClientErrorException();
      } else if (statusCode >= 500 && statusCode < 600) {
        throw ServerErrorException();
      } else {
        throw UnknownException();
      }
    } on SocketException {
      throw ConnectionException();
    }
  }
}

Can anyone help me with this?

1

There are 1 best solutions below

0
On

Using Wakelock plugin, we can solve this problem, but I don't know this is the best solution or not. Note: This plugin works for all the platforms except linux.

Add the below code in the screen where you are initiating the api request.

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    checkAndEnableWakeLock();
  }

  void checkAndEnableWakeLock() async {
    bool wakeLockEnabled = await Wakelock.enabled;
    if (!wakeLockEnabled) {
      Wakelock.enable();
    }
  }

Call disable method when all the api calls are completed.

Wakelock.disable();

Using above code you can avoid screen getting off issue.