Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Focusable Action Detector In Flutter

Whenever you will code for building anything in Flutter, it will be inside a widget. The focal design is to assemble the application out of gadgets. It depicts how your application view should look with its ongoing design and state. Right when you made any change in the code, the gadget adjusts its portrayal by working out the separation between the past and current widget to pick the irrelevant changes for conveying in the UI of the application.

In Flutter, to build any application, we start with widgets. The construction block of flutter applications. Widgets portray what their view should look like given their current setup and state. It consolidates a text widget, line widget, segment widget, container widget, and some more.

While building a custom UI control in Flutter it’s enticing to simply utilize a GestureDetector and tap out, yet to do so would be a mix-up! Particularly assuming you’re anticipating supporting clients with alternate inputs like a mouse or keyboard.

In this article, we will explore the Focusable Action Detector. We will implement the Focusable action detector demo program and learn how to use the same in your flutter applications.

FocusableActionDetector class – widgets library – Dart API
API docs for the FocusableActionDetector class from the widgets library, for the Dart programming language.api.flutter.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Focusable Action Detector:

Constructor

Properties

Code Implement

Code File

Conclusion

GitHub Link


Incidentally, making a UI control that acts “appropriately” for different input sources is a lot more confounded than simply detecting taps. Generally, the control you make needs the accompanying 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)

Focusable Action Detector:

FocusableActionDetectorcombinesFocus,Actions,Shortcuts andMouseRegioninto one, and is used pretty heavily inside of the Flutter SDK, including the Material DatePicker,Switch,Checkbox,RadioandSlider controls.

Customarily, you could make that by making a significant block out of widgets including Focus, Actions, Shortcuts, and MouseRegion. This works, however, is a ton of boilerplate, and space. Fortunately, Flutter gives a committed widget for this purpose: FocusableActionDetector.

Demo Module :

This demo shows how the detector works in an app. It shows how the buttons are having focus and hover changes and mouse changing regions.

Constructor:

To utilize Focusable Action Detector, you need to call the constructor underneath:

FocusableActionDetector({
Key key,
bool enabled = true,
bool autofocus = false,
FocusNode? focusNode,
bool descendantsAreFocusable = true
,bool descendantsAreTraversable = true
,Map<ShortcutActivator, Intent>? shortcuts,
Map<Type, Action<Intent>>? actions,
ValueChanged<bool>? onShowFocusHighlight,
ValueChanged<bool>? onShowHoverHighlight,
ValueChanged<bool>? onFocusChange,
MouseCursor mouseCursor = MouseCursor.defer,
@required Widget child,
});

In Above Constructor all fields marked with @required must not be empty.

Properties:

There are some properties of FocusableActionDetector:

  • > actions → Map<Type, Action<Intent>>?A map of Intent keys to Action<Intent> objects that defines which actions this widget knows about.
  • > autofocus → bool True if this widget will be selected as the initial focus when no other node in its scope is currently focused.
  • > child → Widget The child widget for this FocusableActionDetector widget.
  • > descendantsAreFocusable → bool If false, will make this widget’s descendants unfocusable.
  • > descendantsAreTraversable → bool If false, will make this widget’s descendants untraversable.
  • > enabled → boolIs this widget enabled or not.
  • > focus Node → FocusNode?An optional focus node to use as the focus node for this widget.
  • > mouse Cursor → MouseCursorThe cursor for a mouse pointer when it enters or is hovering over the widget.
  • > onFocus Change → ValueChanged<bool>?A function that will be called when the focus changes.
  • > onShowFocusHighlight → ValueChanged<bool>?A function that will be called when the focus highlight should be shown or hidden.
  • > onShowHoverHighlight → ValueChanged<bool>?A function that will be called when the hover highlight should be shown or hidden.
  • > shortcuts → Map<ShortcutActivator, Intent>?The map of shortcuts that the ShortcutManager will be given to manage.

How to implement code in dart file:

You need to implement it in your code respectively:

Create a new dart file calledbutton.dart inside thelib folder.

To start with, make a StatefulWidget that can hold your _isFocused and _isHovered state. We’ll likewise make a FocusNode that we can use to demand focus on press, which is a typical way of behaving for buttons. Likewise, make some run of the mill onPressed and label fields to design the button.

class MyCustomButton extends StatefulWidget {
@override
State<MyCustomButton> createState() => _MyCustomButtonState();
}

class _MyCustomButtonState extends State<MyCustomButton> {
bool _isHovered = false;
bool _isFocused = false;
FocusNode _focusNode = FocusNode();

@override
Widget build(BuildContext context) {
// TODO:
}

void _handlePressed() {
_focusNode.requestFocus();
widget.onPressed();
}
}

Because we’re making a button, we’ll add some basic configuration options:

const MyCustomButton({Key? key, 
required this.onPressed, 
required this.label}) : super(key: key);
final VoidCallback onPressed;
final String label;
final Color color1;
final Color color2;

When we run the application, we ought to get the screen’s output like the underneath screen capture.

All that’s left now, is to fill out the build() method.

Widget build(BuildContext context) {
Color outlineColor = _isFocused ? Colors.black : Colors.transparent;
Color bgColor = _isHovered ? widget.color1 : widget.color2;
return GestureDetector(
onTap: _handlePressed,
child: FocusableActionDetector(
mouseCursor: SystemMouseCursors.click,
onShowFocusHighlight: _handleFocusHighlight,
onShowHoverHighlight: _handleHoveHighlight,
actions: {
ActivateIntent:
CallbackAction<Intent>(onInvoke: (_) => _handlePressed()),
},
shortcuts: const {
SingleActivator(LogicalKeyboardKey.keyZ, control: true):
ActivateIntent(),
},
child: Container(
padding: const EdgeInsets.all(8),
child: Text(widget.label),
decoration: BoxDecoration(
color: bgColor,
border: Border.all(color: outlineColor, width: 2),
),
),
),
);
}

In the above code, note that you still do need to wrap a GestureDetector to detect taps. Additionally, notice how you can change the appearance of your UI, according to the hover/focus state.

keyboard actions:

The final step for any control is Keyboard bindings. By default, most OS controls support [Space] and [Enter] to “submit”. You can do this by wiring up the built-in ActivateIntent in the .actions field:

FocusableActionDetector(
actions: {
ActivateIntent: CallbackAction<Intent>(onInvoke: (_) => _handlePressed()),
},
child: ...
),

You can also add additional key bindings using the .shortcuts parameter. Here we’ll bind yet [Ctrl + Z] to the same ActivateIntent. Now our control will submit on [Enter], [Space] and [Ctrl + Z]!

FocusableActionDetector(
shortcuts: {
SingleActivator(LogicalKeyboardKey.keyZ, control: true): ActivateIntent(),
},
child: ...
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

With that, you have a finished control that works exactly as you’d expect on desktop, web, and mobile! keyboard actions

Code File:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MyCustomButton extends StatefulWidget {
const MyCustomButton(
{Key? key,
required this.onPressed,
required this.label,
required this.color1,
required this.color2})
: super(key: key);
final VoidCallback onPressed;
final String label;
final Color color1;
final Color color2;

@override
State<MyCustomButton> createState() => _MyCustomButtonState();
}

class _MyCustomButtonState extends State<MyCustomButton> {
bool _isHovered = false;
bool _isFocused = false;
final FocusNode _focusNode = FocusNode();

void _handleFocusHighlight(bool value) {
setState(() {
_isFocused = value;
});
}

void _handleHoveHighlight(bool value) {
setState(() {
_isHovered = value;
});
}

@override
Widget build(BuildContext context) {
Color outlineColor = _isFocused ? Colors.black : Colors.transparent;
Color bgColor = _isHovered ? widget.color1 : widget.color2;
return GestureDetector(
onTap: _handlePressed,
child: FocusableActionDetector(
mouseCursor: SystemMouseCursors.click,
onShowFocusHighlight: _handleFocusHighlight,
onShowHoverHighlight: _handleHoveHighlight,
actions: {
ActivateIntent:
CallbackAction<Intent>(onInvoke: (_) => _handlePressed()),
},
shortcuts: const {
SingleActivator(LogicalKeyboardKey.keyZ, control: true):
ActivateIntent(),
},
child: Container(
padding: const EdgeInsets.all(8),
child: Text(widget.label),
decoration: BoxDecoration(
color: bgColor,
border: Border.all(color: outlineColor, width: 2),
),
),
),
);
}

void _handlePressed() {
_focusNode.requestFocus();
widget.onPressed();
}
}

Conclusion:

In the article, I have explained the essential construction of the Focusable Action Detector widget in a flutter application; you can alter this code as indicated according to your choice. This was a little prologue to the Focusable Action Detector widget on User Interaction from my side, and its functioning utilizing Flutter.

I hope this blog will provide you with sufficient information on Trying up the Focusable Action Detector widget in your flutter projects. We showed you what the Focusable Action Detector widget is?, its constructor, and its properties of the Focusable Action Detector widget. We made a demo program for working Focusable Action Detector widget. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

find the source code of the focusable_action_detector:

GitHub – flutter-devs/focusable_action_detector_example
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Leave comment

Your email address will not be published. Required fields are marked with *.