Flutter App that print message when headset button press by user

288 Views Asked by At

Can any one help me i used so many pub.dev package but i cannot find my answer

I try on this packages

  • audio_service 0.18.9
  • headset_connection_event
  • flutter_headset_detector
1

There are 1 best solutions below

0
On BEST ANSWER

It should be easily possible with the hardware_buttons package (https://pub.dev/packages/hardware_buttons), which allows you to listen to hardware button events in your Flutter app.

Since the Hardwarebuttons on a headset fire the same event as the buttons on your phone or even keyboard this should be possible:

void _listenToHardwareButtons() {
  hardwareButtons.volumeButtonEvents.listen((event) {
    if (event == hardwareButtons.VolumeButtonEvent.VOLUME_UP) {
      print('Volume Up button pressed on headset');
    } else if (event == hardwareButtons.VolumeButtonEvent.VOLUME_DOWN) {
      print('Volume Down button pressed on headset');
    }
  });
}

You might need to add the required permissions for listening to hardware button-events in the androidmanifest.xml. I did not need to surprisingly.

This should even work on iOS now. But i could not try this out since i don't have an iPhone with me currently.

If you only want to listen to the VolumeKeys you might want to check out: https://pub.dev/packages/volume_watcher

For Desktop/Web:

You can use Focus widget or RawKeyboardListener widget to listen to keyboard events:

  Focus(
    autofocus: true,
    focusNode: FocusNode(),
    onKeyEvent: (node, event) {
      if (event.physicalKey == PhysicalKeyboardKey.audioVolumeUp) {
        return KeyEventResult.handled;
      }
      return KeyEventResult.ignored;
    },
    child: Container(),
  ),