-1

I am building an app that starts by pressing the hardware button (Android/ios volume up button) for a long time, but I can't find any way to do it, Is there any way to do it?

Anurag Yadav
  • 199
  • 1
  • 1
  • 9

1 Answers1

1

UPDATED ANSWER:

For iOS/Android:

check out this package:


For Desktop/Web:

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

Here's a simple example:

@override
Widget build(BuildContext context) {
  return Focus(
    autofocus: true,
    onKeyEvent: (node, event) {
      if (event.physicalKey == PhysicalKeyboardKey.keyA) {
        if (event is KeyDownEvent) {
          // the user started pressing the key A
        } else if (event is KeyRepeatEvent) {
          // the user is pressing the key A
        } else if (event is KeyUpEvent) {
          // the user stopped pressing the key A
        }
        // if you handled the event (prevent propagating the events further)
        return KeyEventResult.handled;
      }
      // otherwise return this (propagates the events further to be handled elsewhere)
      return KeyEventResult.ignored;
    },
    child: Container(),
  );
}

I'm using a macbook with touchbar so I couldn't confirm the volume up but you can replace PhysicalKeyboardKey.keyA with PhysicalKeyboardKey.audioVolumeUp.

Also, instead of using autofocus, you can use a FocusNode and pass it to the Focus widget to control when the widget has focus (i.e. when it should listen to events).

References:

osaxma
  • 2,657
  • 2
  • 12
  • 21
  • @AnuragYadav my old answer was for Desktop/Web only -- for iOS/Android, check the updated answer -- there's a package called [Volume Watcher](https://pub.dev/packages/volume_watcher) – osaxma Jan 27 '22 at 14:01
  • thanks for your help but, I want it to detect button press in the background even when the device is locked. is there any such way in flutter or nay such library? or do I need to write platform-specific code? – Anurag Yadav Jan 27 '22 at 14:27
  • Here is a brief of what I want. Suppose I am making an app that turns on the flashlight on when starts, so at any point when volume button is pressed for 5 seconds it starts the app – Anurag Yadav Jan 27 '22 at 14:34
  • @AnuragYadav I'm not very familiar with this area to be honest but this answer may be helpful: https://stackoverflow.com/a/62641923/10976714 – osaxma Jan 27 '22 at 14:45