How to send data to server in background in flutter?

Viewed 469

When using workmanager: ^0.2.3 I have been able to do some work in the background but I can't send data to the sever using the http package in the background. It simply doesn't happen when it gets to the api call.

This is what I've written in main:

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    switch (task) {
      case simpleTaskKey:
        await sendUnsentDataToServerIfOffline(inputData);
        break;
    }
    return Future.value(true);
  });
}

void sendDetailsAPIFromWorker(
    List<Details> detailsToSent, Map<String, dynamic> inputData) async {

  List<TDetails> tDetails = [];
  detailsToSent.forEach((detail) => tDetails.add(TDetails(
      serviceTime: detail.serviceTime,
      fromStopTime: detail.fromStopTime,
      toStopTime: detail.toStopTime,
      submitType: detail.submitType,
      status: detail.status,
      travelledDistance: 0.0)));
  SendDetails sendDetail = SendDetails(
      userToken: inputData['token'],
      missionId: inputData['service_id'],
      details: tDetails);
  Map<String, String> requestHeaders = {
    'Content-type': 'application/json',
    'Accept': 'application/json'
  };
  try {
    final url = '${inputData['base_url']}$kAPISubmitMissionTransportURL';
    try {
      final response = await http.post(url,
          headers: requestHeaders, body: json.encode(sendDetail.toJson()));

      if (json.decode(response.body)['Status'] == 1) {
        detailsToSent.forEach((detail) => DBHelper.deleteStopTransportData(
            kTransportDetailsTableName,
            inputData['service_id'],
            detail.serviceDetailId));
        List<int> ids = [];
        await detailsToSent
            .forEach((detail) => ids.add(detail.serviceDetailId));
        print('ids to to set send: $ids');
        await DBHelper.setDetailSent(
            kTransportDetailsTableName, ids, inputData['service_id']);
      }
    } catch (error) {

    }
  } catch (error) {
    print(error);
  }
}
0 Answers
Related