I have the android device you see in the picture. This device has an orange button on the back. I want to trigger a certain function when this button is pressed. I just try to use the HardwareKeyboard in Flutter as below and get a solution, but I don't get a response.enter image description here
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {
HardwareKeyboard.instance.addHandler(key_handler);
super.initState();
}
bool key_handler(event) {
print(event.physicalKey.debugName);
// In this part, when a button is clicked, it should return certain responses to me.
if (event is KeyDownEvent) {
if (event.physicalKey.usbHidUsage == PhysicalKeyboardKey.audioVolumeDown.usbHidUsage) {
_incrementCounter();
} else if (event.physicalKey.usbHidUsage ==
PhysicalKeyboardKey.audioVolumeUp.usbHidUsage) {
_decrementCounter();
}
}
return true;
}
void _incrementCounter() {
setState(() {
_counter ;
});
}
void _decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Hit a Volume UP/Down key:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
TextField(
decoration: InputDecoration(
hintText: "Once touch here and show a software key."),
),
],
),
),
);
}
}
The code above increments or decrements the count by 1 unit when the volume up and down buttons are pressed. It works.
The button I need is known as f4 on the back. But when I click on this button I don't get any response.
I think Flutter has this problem because the codes of this part are not complete. Because there is no response from any button except the volume up and down buttons, the back button.
There is no Plugin that I can find to solve this issue. There used to be a plugin called hardware_buttons. Currently unavailable. Because it was written 3 years ago and the update has not arrived. I think since Flutter added HardwareKeyboard to itself, it was no longer needed.
Please write all the guesses you know and guess in the comment section.
CodePudding user response:
Since the answer to the above question could not be solved on the Flutter side, I had to write the following package. Those facing this question can use it.