Sub topic 12
Adapting to touch, mouse and keyboard
This chapter assumes you can build widget trees with StatefulWidget, you know Scaffold and ListView, and you have run a Flutter app on a desktop or web target. Window size is one part of adapting a layout. The other part is how the user points at things. A phone user taps with a thumb. A laptop user hovers, right-clicks, scrolls with a wheel and presses Tab. One window width can come with any of these.
Size does not tell you the input device
It is tempting to assume that a compact window means touch and an expanded window means mouse. That breaks in several common cases:
- A tablet in landscape has an expanded window and is used with fingers.
- A narrow desktop window is still driven by a mouse and keyboard.
- A convertible laptop switches between touch and trackpad in the same session.
- A phone can have a Bluetooth keyboard attached.
Treat layout and input as two separate decisions. Breakpoints decide how much content fits. Input handling decides how each control behaves. Build every control to work with all three inputs, then add extras such as hover feedback and shortcuts where a pointer or keyboard is available.
| Concern | Touch | Mouse | Keyboard |
|---|---|---|---|
| Target size | Large, about 48 logical pixels | Can be smaller and denser | Same as pointer |
| Feedback | Ripple on press | Hover highlight and cursor change | Visible focus indicator |
| Secondary actions | Long press | Right-click | Shortcut or menu key |
| Scrolling | Drag | Wheel, scrollbar, trackpad | Arrow keys, Page Up, Page Down |
How input events travel
Pointer events (touch, mouse, stylus, trackpad) and key events take different routes through the widget tree. Pointer events go to the widgets under the pointer. Key events go to the widget that has focus, then bubble up through its ancestors.
This difference explains the most common keyboard bug. If nothing has focus, no key event reaches your Shortcuts widget, and the shortcut seems dead.
Hover and cursor feedback
A touch screen has no hover state, so hover feedback is an extra for pointer users. The built-in Material buttons and InkWell already handle hover, focus and cursor. Prefer them to custom gesture code, because they also respond to Enter and Space when focused. A custom GestureDetector does neither.
When you need your own hover styling, use InkWell.onHover or a MouseRegion:
import 'package:flutter/material.dart';
class HoverTile extends StatefulWidget {
const HoverTile({super.key, required this.label, required this.onOpen});
final String label;
final VoidCallback onOpen;
@override
State<HoverTile> createState() => _HoverTileState();
}
class _HoverTileState extends State<HoverTile> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return InkWell(
onTap: widget.onOpen,
onHover: (value) => setState(() => _hovered = value),
mouseCursor: SystemMouseCursors.click,
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
constraints: const BoxConstraints(minHeight: 48),
padding: const EdgeInsets.symmetric(horizontal: 16),
alignment: Alignment.centerLeft,
color: _hovered ? scheme.surfaceContainerHighest : null,
child: Text(widget.label),
),
);
}
}Hover must never be the only way to reach something. A tooltip that appears on hover is fine. An action that appears only on hover is invisible to touch users. Show those actions always, or add a long-press or overflow-menu alternative.
Touch target size
Fingers are imprecise, so Material guidance asks for tap targets of at least 48 by 48 logical pixels. Mouse users can work with denser layouts. Material widgets read VisualDensity from the theme, and its default depends on the platform. Desktop platforms default to a compact density and mobile platforms to a standard one.
Do not rely on that default alone. A touch-screen laptop is a desktop platform, yet it still receives finger taps. Keep a 48-pixel minimum on interactive items unless you have a reason not to. If you want to adapt, base it on the pointer that was last used, not on the platform:
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
class InputKindBuilder extends StatefulWidget {
const InputKindBuilder({super.key, required this.builder});
final Widget Function(BuildContext context, PointerDeviceKind? lastKind)
builder;
@override
State<InputKindBuilder> createState() => _InputKindBuilderState();
}
class _InputKindBuilderState extends State<InputKindBuilder> {
PointerDeviceKind? _kind;
void _update(PointerEvent event) {
if (event.kind != _kind) {
setState(() => _kind = event.kind);
}
}
@override
Widget build(BuildContext context) {
return Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: _update,
onPointerHover: _update,
child: widget.builder(context, _kind),
);
}
}A builder can then use lastKind == PointerDeviceKind.touch to choose a taller row. onPointerHover only fires for devices that can hover, so a touch-only device reports its kind from onPointerDown. Until the first event, lastKind is null. Treat null as the safe default of large targets.
Scrolling with a mouse
Flutter's default scroll behavior does not let a mouse drag a scrollable. A finger drag scrolls a list, but a mouse drag does not. Wheel scrolling and scrollbars still work. Desktop and web users therefore usually have what they need, but a mouse drag can look broken if your design expects it. You can allow it by overriding dragDevices:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class AppScrollBehavior extends MaterialScrollBehavior {
@override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
PointerDeviceKind.trackpad,
PointerDeviceKind.stylus,
};
}Pass it with MaterialApp(scrollBehavior: AppScrollBehavior(), ...). Think before enabling mouse drag. It conflicts with text selection and with horizontal sliders inside the scrollable. Many apps leave the default and rely on the wheel and the scrollbar.
Material apps show a scrollbar automatically on desktop platforms. For a scrollable nested inside a page, wrap it in a Scrollbar and give both the same ScrollController. Without a shared controller, the scrollbar can report that it has no position.
Keyboard: focus, shortcuts and actions
Flutter separates what a key press means from what it does. A Shortcuts widget maps a key combination to an Intent, which is a small object that names a request. An Actions widget maps the intent type to the code that runs. The split lets a menu item, a button and a shortcut all trigger the same action.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class IncrementIntent extends Intent {
const IncrementIntent();
}
void main() => runApp(const MaterialApp(home: CounterPage()));
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
void _increment() => setState(() => _count++);
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.keyN, control: true):
IncrementIntent(),
SingleActivator(LogicalKeyboardKey.keyN, meta: true):
IncrementIntent(),
},
child: Actions(
actions: <Type, Action<Intent>>{
IncrementIntent: CallbackAction<IncrementIntent>(
onInvoke: (intent) {
_increment();
return null;
},
),
},
child: Focus(
autofocus: true,
child: Scaffold(
body: Center(child: Text('Count: $_count')),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
tooltip: 'Add (Ctrl+N or Cmd+N)',
child: const Icon(Icons.add),
),
),
),
),
);
}
}Three details matter here:
- The two
SingleActivatorentries cover Ctrl on Windows and Linux and Command on macOS. Registering both is simpler than checking the platform. Focus(autofocus: true)gives the subtree a focused node. Without it, a page with no focused widget receives no key events.- The tooltip documents the shortcut. A shortcut nobody can discover helps few users.
A shortcut can also steal keys from a text field. If a user types "n" with Ctrl held in a TextField, your intent runs first only if your Shortcuts is an ancestor of the field and the field does not handle the key. Text fields handle plain character keys themselves, but modified combinations such as Ctrl+N pass through. Avoid combinations that conflict with text editing, such as Ctrl+A, Ctrl+C and Ctrl+V.
Tab order and visible focus
Tab moves focus through interactive widgets in a default reading order. Material buttons, text fields and InkWell join the order automatically. If the order is wrong, wrap a section in FocusTraversalGroup with an OrderedTraversalPolicy and mark widgets with FocusTraversalOrder. Do not remove the focus highlight to make a design cleaner. Keyboard users rely on it to know where they are.
Right-click and long press
A secondary click is the mouse counterpart of a long press. Support both for the same action, so no input device is left out:
- Use
GestureDetector.onSecondaryTapUpfor right-click, andonLongPressfor touch. - Show a
showMenuorMenuAnchorat the pointer position. - Wrap read-only text in
SelectionAreaso mouse users can select and copy it. On the web, this also supports the browser's selection behavior.
Common errors
- Hover-only controls, which touch users cannot reach.
- Custom
GestureDetectorbuttons that ignore keyboard focus. UseInkWell,TextButtonorFocusableActionDetectorinstead. - Shortcuts with no focused widget, so no key event arrives.
- Small desktop-density rows on a touch screen.
- Choosing input handling from
MediaQuerywidth, which says nothing about the device.
Exercise
A list item action button is shown only while the mouse hovers over the row. It works on your laptop, but testers on tablets report that it is missing. Why does it fail, and how would you fix it?
Show answer
A touch screen produces no hover events, so the button is never shown. Fix it by making the action reachable without hover: either show it always, or add a long-press or overflow-menu alternative. Keep hover highlighting only as an extra on top of that. Also check that the row can take keyboard focus so keyboard users can reach the action.
Exercise
Your Ctrl+N shortcut is registered in a Shortcuts widget, but pressing the keys does nothing. Name two causes and a fix for each.
Show answer
First, no widget in the subtree has focus, so no key event reaches Shortcuts. Fix it by adding a Focus widget with autofocus: true below Shortcuts, or by requesting focus from a FocusNode. Second, on macOS the user presses Command, not Control. Fix it by registering a second SingleActivator with meta: true. A third possible cause is that the Actions widget has no entry for the intent type, in which case the key matches but nothing runs.