Flutter : Detect keyboard event in CustomPainter

TrueulyMarket
1 min readApr 4, 2024

To detect keyboard events in your Flutter app while using a CustomPaint widget, you can create a RawKeyboardListener as a parent widget to capture keyboard events. Then you can pass the callback function down to your CustomPaint widget as an argument.

First, create a function to handle the key events in your custom painter:

typedef OnKeyEvent = Function(RawKeyEvent event);



class TerminalScreen extends CustomPainter {

TerminalScreen({required this.message, required this.control, required this.onKeyEvent});



final String message;

final Control control;

final OnKeyEvent onKeyEvent;

}

Then, use RawKeyboardListener to capture the keyboard events:

RawKeyboardListener(

focusNode: FocusNode(),

onKey: (RawKeyEvent event) {

// Pass the event to your custom painter

yourCustomPainter.onKeyEvent(event);



// Return true to consume the event

return true;

},

child: CustomPaint(

painter: TerminalScreen(

message: _terminalData,

control: control,

onKeyEvent: (event) {

// Handle keyboard events in your custom painter

},

),

),

)

Now, in your TerminalScreen class, you can use the onKeyEvent callback function to handle the keyboard events in the paint method or any other place you find suitable.

--

--