Flutter: Keyboard & Mouse Support for Web
tl;dr
I am working on a Flutter project primarily for the Web (of course, supported on devices as well). Keyboard and mouse actions are an absolute must and an MVP (minimal viable product). I want to share how have I used FocusableActionDetector to support both the keyboard and mouse.
For a quick overview just refer to the ‘Sample App’ & ‘Screen Recording’ sections below.
Sample App
I have a sample app where I have used FocusableActionDetector to listen to both keyboard and mouse. Below are the details of the app and Github repo.
Searchbox like Gmail with Overlay widget: Simple app to demonstrate the use of Overlay widget to create Gmail like Searchbox.
Click here to see it in action.
Click here for the link to the Medium story.
Github
Click here for the source code. Refer x_fad.dart for custom FocusableActionDetector widget.
Flutter Documentation + Medium
As always flutter documentation is amazing.
This Medium story is great (my starting point) to get in-depth understanding on FocusableActionDetector.
Screen Recording
What is implemented in this use case?
A simple widget (XFAD) that wraps FocusableActionDetector with optional callbacks. This helps avoid boilerplate code on every widget that needs keyboard and mouse actions.
Keyboard: Listening to a few keys for this sample project: Escape, Tab, Arrow Up, Arrow Down + Key combinations like (Shit + Tab).
Mouse: Hover callback (custom hover implementation)
Example 1
Handling Escape, Tab, and Shift + Tab when a TextFormField has focus. (Line # 2, 3 & 4 are callbacks for specific keys. Refer search_options_screen.dart)
Note: “Enter” key is handled using “onFieldSubmitted” property of TextFormField (cannot be handled with FAD)
Example 2
Navigating suggest list with “Arrow Down”, “Arrow Up” keys, or Use of hover callback to highlight selected item in the list.
Note: “hoverColor” property of ListTile is set to transparent to use custom styling with blue left border side.
Refer _keyboardSupport(..) method of main.dart and random_list_screen.dart for implementation details.
Other features
- Handle focus through “onFocusChange” and “onShowFocusHighlight” properties (not used in my sample).
- I have used an extension on “Widget” to change the mouse cursor.
We can use “mouseCursor” property of FocusableActionDetector instead of the above technique and avoid dealing with DOM.
CONCLUSION
The use of FocusableActionDetector is simple and inevitable when we are developing Flutter web or desktop apps. I am hoping in the near future Flutter default widgets will handle basic keyboard support and the use of FocusableActionDetector will be limited to special and custom use cases.
Thank you.
Vinay
Follow Flutter Community on Twitter: https://www.twitter.com/FlutterComm