Flutter local notification action button

I’m attempting to add an action button to some of my received push notifications, I’m using Flutter Local Notifications with FCM to listen to incoming data (from my server) and create the notification.
Currently, when I tap on the notification, it opens the app (which is okay for me), but I want to call an API server method when the user taps on the action button. I’ve tried many methods, but I haven’t succeeded in making it work. Actually, when I tap on the button, nothing happens. Can someone help me fire the action button event when tapped?
Thanks in advance.

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = 

FlutterLocalNotificationsPlugin();
var firebaseMessaging = FirebaseMessaging.instance;

// Listening to the background messages
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage? message) async {
  showNotification(message);
}

// Show local notification
Future<void> showNotification(RemoteMessage? message) async {
  var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
    'channel_id', 'channel_name',
    importance: Importance.max,
    priority: Priority.high,
    icon: "ic_launcher",
    actions: [
      AndroidNotificationAction('action_1', 'API Call'),
    ]
  );
  
  // var iOSPlatformChannelSpecifics = IOSNotificationDetails();
  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics);

  if(message?.notification == null){
    if(message?.data != null){
      await flutterLocalNotificationsPlugin.show(
          0, message?.data["title"], message?.data["content"], platformChannelSpecifics,
          payload: 'item x');
    }
  }
}

void main() async{
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Firebase
  await Firebase.initializeApp(options: FirebaseConfig.defaultFirebaseOptions);

  await firebaseMessaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  // Listening to the background messages
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  // Listening to the foreground messages
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    showNotification(message);
  });

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => myprovider1()),
        ChangeNotifierProvider(create: (context) => myprovider2()),
        ChangeNotifierProvider(create: (context) => myprovider3())
      ],
      child: MyApp(),
    ),
  );
}

enter image description here

Leave a Comment