Ad
How To Change The Color Of A Container By Holding A Key (hold Key Listener )
I’m trying to change the color of a container by holding a specific key for example
if i’m holding the space i want the container to be black and when i release it i want to go back the original color
im using a RawKeyboardlistener
widget but it’s not working the way i want
it just executes over and over when i hold down the key
RawKeyboardListener(
autofocus: true,
focusNode: FocusNode(),
onKey: (event) {
List<LogicalKeyboardKey> keys = [];
final key = event.logicalKey;
if (event is RawKeyDownEvent) {
if (keys.contains(key)) return;
if (event.isKeyPressed(LogicalKeyboardKey.space)) {
print('SPACE PRESSED');
IsSpacePressed = !IsSpacePressed;
}
setState(() {
keys.add(key);
});
} else {
setState(() {
keys.remove(key);
IsSpacePressed = !IsSpacePressed;
});
}
},
Ad
Answer
Here is a simplified version that could also work for the expected result.
RawKeyboardListener(
autofocus: true,
focusNode: FocusNode(),
onKey : (event) {
if(event is RawKeyDownEvent && event.isKeyPressed(LogicalKeyboardKey.space){
print('SPACE PRESSED DOWN');
IsSpacePressed = true;
}
else if(event is RawKeyUpEvent && event.logicalKey == LogicalKeyboardKey.space) {
print('SPACE UP RELEASE');
IsSpacePressed = false;
}
setState(() {});
},
child : Container(
height : 200.0,
width : 200.0,
color : IsSpacePressed ? Colors.red : Colors.black,
),);
Ad
source: stackoverflow.com
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad