Flutter WorkManager And PushNotification Callback Execution Issue

Viewed 600

I am working on work manager to fetxh api data and initiate a notification in flutter,

    //this is the name given to the background fetch
    const simplePeriodicTask = "simplePeriodicTask";
    Workmanager workmanager = Workmanager();
    // flutter local notification setup

    Future initializeWorkManagerAndPushNotification() async {
      await workmanager.initialize(
        callbackDispatcher,
        isInDebugMode: false,
      ); //to true if still in testing lev turn it to false whenever you are launching the app
      await workmanager.registerPeriodicTask(
        "1", simplePeriodicTask,
        existingWorkPolicy: ExistingWorkPolicy.replace,
        frequency: Duration(minutes: 1), //when should it check the link
        initialDelay:
            Duration(seconds: 5), //duration before showing the notification
        constraints: Constraints(
          networkType: NetworkType.connected,
        ),
      );
    }

    void callbackDispatcher() async {
      workmanager.executeTask((task, inputData) async {
        print('Ruuning - callbackDispatcher');
        FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
            FlutterLocalNotificationsPlugin();
        var androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
        var iOSSettings = IOSInitializationSettings();
        var initSetttings =
            InitializationSettings(android: androidSettings, iOS: iOSSettings);

        //
        // TODO: Permission
        //
        await flutterLocalNotificationsPlugin.initialize(initSetttings);

        String message =
            await WebServiceController.getInstance.getPushNotificationMessage();
        print("here 1 ================");
        // print(response);
        // var convert = json.decode(response.body);
        // if (convert['status'] == true) {
        //   showNotification(convert['msg'], flutterLocalNotificationsPlugin);
        // } else {
        //   print("no messgae");
        // }
        print("messgae");
        print(message);
        await showNotification(message, flutterLocalNotificationsPlugin);

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

    Future showNotification(payloadmessage, flutterLocalNotificationsPlugin) async {
      print("showing notification");
      var androidDetails = AndroidNotificationDetails(
          'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
          priority: Priority.high, importance: Importance.max);
      var iOSDetails = IOSNotificationDetails();
      var platform = NotificationDetails(android: androidDetails, iOS: iOSDetails);
      await flutterLocalNotificationsPlugin.show(
          0, 'Message - Virtual intelligent solution', '$payloadmessage', platform,
          payload: 'OnClick Payload -VIS \n $payloadmessage');
    }

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

      await initializeWorkManagerAndPushNotification();

      runApp(MyApp());
    }

this function callbackDispatcher() function is used to Initialize Notification and fetch api data from below method.

    Future<String> getPushNotificationMessage() async {
      print("getting - getPushNotificationMessage");
      try {
        var response = await _dio.get(APIURLConstants.pushNotification);
        print(response);
        print("here================ ${response.data}");
        var convert = json.decode(response.data);
        return convert['message'].toString() ?? "";
      } on DioError catch (error) {
        print("Dio Error ${error.message}");
      } catch (error) {
        print("Error - ${error.toString()}");
      }
    }

as per the below output , It seems that only print(response); of getPushNotificationMessage() is executed after that below code is not executing,

    Performing hot restart...
    Restarted application in 2,266ms.
    W/WM-WorkSpec(31092): Interval duration lesser than minimum allowed value; Changed to 900000
    I/flutter (31092): getting - getPushNotificationMessage
    I/flutter (31092): {"message":"Hi There I am notification","seen":0,"notification_id":"111"}
    I/WM-WorkerWrapper(31092): Worker result SUCCESS for Work [ id=6c935b3b-bfe4-47fa-b30a-0965299f5224, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
1 Answers

I founded the issue, to make the code execute, I needed to hot restart the application to execute code from

  main() method
Related