diff --git a/packages/flutter/lib/src/semantics/semantics_event.dart b/packages/flutter/lib/src/semantics/semantics_event.dart index be391cbadd..ce2759e774 100644 --- a/packages/flutter/lib/src/semantics/semantics_event.dart +++ b/packages/flutter/lib/src/semantics/semantics_event.dart @@ -159,3 +159,71 @@ class TapSemanticEvent extends SemanticsEvent { @override Map getDataMap() => const {}; } + +/// An event to move the accessibility focus. +/// +/// Using this API is generally not recommended, as it may break a users' expectation of +/// how a11y focus works and therefore should be just very carefully. +/// +/// One possibile use case: +/// For example, the currently focused rendering object is replaced by another rendering +/// object. In general, such design should be avoided if possible. If not, one may want +/// to refocus the newly added rendering object. +/// +/// One example that is not recommended: +/// When a new popup or dropdown opens, moving the focus in these cases may confuse users +/// and make it less accessible. +/// +/// {@tool snippet} +/// +/// The following code snippet shows how one can request focus on a +/// certain widget. +/// +/// ```dart +/// class MyWidget extends StatefulWidget { +/// const MyWidget({super.key}); +/// +/// @override +/// State createState() => _MyWidgetState(); +/// } +/// +/// class _MyWidgetState extends State { +/// bool noticeAccepted = false; +/// final GlobalKey mykey = GlobalKey(); +/// +/// @override +/// void initState() { +/// super.initState(); +/// // Using addPostFrameCallback because changing focus need to wait for the widget to finish rendering. +/// WidgetsBinding.instance.addPostFrameCallback((_) { +/// mykey.currentContext?.findRenderObject()?.sendSemanticsEvent(const FocusSemanticEvent()); +/// }); +/// } +/// +/// @override +/// Widget build(BuildContext context) { +/// return Scaffold( +/// appBar: AppBar( +/// title: const Text('example'), +/// ), +/// body: Column( +/// children: [ +/// const Text('Hello World'), +/// const SizedBox(height: 50), +/// Text('set focus here', key: mykey), +/// ], +/// ), +/// ); +/// } +/// } +/// ``` +/// {@end-tool} +/// +/// This currently only supports Android and iOS. +class FocusSemanticEvent extends SemanticsEvent { + /// Constructs an event that triggers a focus change by the platform. + const FocusSemanticEvent() : super('focus'); + + @override + Map getDataMap() => const {}; +} diff --git a/packages/flutter/test/widgets/semantics_event_test.dart b/packages/flutter/test/widgets/semantics_event_test.dart index 4cfd1f6145..164d450734 100644 --- a/packages/flutter/test/widgets/semantics_event_test.dart +++ b/packages/flutter/test/widgets/semantics_event_test.dart @@ -47,6 +47,15 @@ void main() { }, ); }); + test('FocusSemanticEvent.toMap', () { + expect( + const FocusSemanticEvent().toMap(), + { + 'type': 'focus', + 'data': {}, + }, + ); + }); } class TestSemanticsEvent extends SemanticsEvent {