Billy Noyes
Billy Noyes

Reputation: 113

Need help using Flutter Local Notifications and Workmanager to send notifications using API

been stuck on this for a while and hope I can find someone that can help

Trying to send local notifications using an API

JSON being returned by the API call looks like this, just can't get the notifications to send if one of the results has a statustext of 'Completed'

{"error":"none","data":[{"status_text":"Completed","status_id":"6","name":"Billy Noyes","order_id":"TYI-28650","type":"blood"},{"status_id":"0","order_id":"TYI-28651-1","name":"Billy Noyes","status_text":"Awaiting Sample","type":"hair"}]}
const simplePeriodicTask = "simplePeriodicTask";
// flutter local notification setup
void showNotification(v, flp) async {
  var android = AndroidNotificationDetails(
      'channel id', 'channel NAME', 'CHANNEL DESCRIPTION');
  var iOS = IOSNotificationDetails();
  var platform = NotificationDetails(android: android, iOS: iOS);
  await flp.show(0, 'Virtual intelligent solution', '$v', platform,
      payload: 'VIS \n $v');
}

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    FlutterLocalNotificationsPlugin flp = FlutterLocalNotificationsPlugin();
    var android = AndroidInitializationSettings('ic_launcher');
    var iOS = IOSInitializationSettings();
    var initSetttings = InitializationSettings(android: android, iOS: iOS);
    flp.initialize(initSetttings);

    var response = await http.post(
        'https://www.testyourintolerance.com/wp-json/app/v1/tracker?token=' +
            loginDataJson["token"]);
    print(response);
    var data = json.decode(response.body);

    for (var i = 0; data["data"].length; i++) {
      if (data["data"][i]["status_text"] == 'Completed') {
        showNotification('One of your results is ready to be viewed!', flp);
      }
    }

    return Future.value(true);
  });
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Both below should be await
  Workmanager.initialize(callbackDispatcher, isInDebugMode: false);
  Workmanager.registerPeriodicTask("1", simplePeriodicTask,
      existingWorkPolicy: ExistingWorkPolicy.replace,
      frequency: Duration(minutes: 15),
      initialDelay: Duration(seconds: 5),
      constraints: Constraints(
        networkType: NetworkType.connected,
      ));
    runApp(
        child: MyApp(),
  });
}

Upvotes: 0

Views: 1130

Answers (1)

Ryan Holder
Ryan Holder

Reputation: 11

I think your for loop needs i < data["data"].length. You should put a breakpoint on the loop to see whether it's running ShowNotification at all. Also, your AndroidInitializationSettings might need to receive @mipmap/ic_launcher.

for (var i = 0; i < data["data"].length; i++) {
  if (data["data"][i]["status_text"] == 'Completed') {
    showNotification('One of your results is ready to be viewed!', flp);
  }
}

Upvotes: 1

Related Questions