When building a custom UI control in Flutter it’s tempting to just use a GestureDetector
and call it a day, but to do so would be a mistake! Especially if you’re planning on supporting users with alternate inputs like mouse or keyboard.
It turns out that making a UI control that behaves “properly” for a variety of inputs is quite a bit more complicated than just detecting taps. Generally speaking, each control you create needs the following features:
Traditionally, you might create that by composing a big block of widgets including Focus
, Actions
, Shortcuts
and MouseRegion
. This works, but is a lot of boilerplate, and indentation. Luckily Flutter provides a dedicated widget for this purpose: FocusableActionDetector
.
FocusableActionDetector
combines Focus
, Actions
, Shortcuts
and MouseRegion
into one, and is used pretty heavily inside of the Flutter SDK, including the Material DatePicker
, Switch
, Checkbox
, Radio
and Slider
controls.
Using it yourself is fairly straightforward. Lets look at how we’d build a completely custom button using this widget.
_Note: To follow along with the code, check out the gist here: _https://gist.github.com/esDotDev/04a6301a3858769d4baf5ab1230f7fa2
First, create a StatefulWidget
that can hold your _isFocused
and _isHovered
state. We’ll also create a FocusNode
that we can use to request focus on press, which is a common behavior for buttons. Also create some typical onPressed
and label
fields to configure the button.
#code #flutter #open source #source code