Home > Net >  how to change the color of a container by holding a key (hold key listener )
how to change the color of a container by holding a key (hold key listener )

Time:12-18

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;
          });
        }
      },

CodePudding user response:

Here is a simplified version that could also work for the expected result.

Link to dart pad

 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,
  ),);
  • Related