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:

  • a hover state
  • a focus state (for tab-key or arrow-key traversal)
  • a region that changes the mouse-cursor
  • key handlers for [Space] and [Enter] keys (or maybe others)

Traditionally, you might create that by composing a big block of widgets including FocusActionsShortcuts and MouseRegion. This works, but is a lot of boilerplate, and indentation. Luckily Flutter provides a dedicated widget for this purpose: FocusableActionDetector.

FocusableActionDetector combines FocusActionsShortcuts and MouseRegion into one, and is used pretty heavily inside of the Flutter SDK, including the Material DatePickerSwitchCheckboxRadio 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

Flutter: Building custom controls with `FocusableActionDetector`
2.80 GEEK