Last active
September 3, 2022 17:06
-
-
Save ndugger/c2aa8078b8029d7d3cde0c17dde578b8 to your computer and use it in GitHub Desktop.
Flutter Focus Management - Full Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/services.dart'; | |
import 'package:flutter/widgets.dart'; | |
const Map<ShortcutActivator, Intent> appShortcuts = { | |
SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(), | |
SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent() | |
}; | |
final Map<Type, Action<Intent>> appActions = { | |
NextFocusIntent: NextFocusAction(), | |
PreviousFocusIntent: PreviousFocusAction() | |
}; | |
class FocusableContainer extends StatelessWidget { | |
const FocusableContainer({ super.key }); | |
@override | |
Widget build(BuildContext context) { | |
return Focus( | |
onFocusChange: (focused) => print('Widget is focused: $focused'), | |
child: Container() | |
); | |
} | |
} | |
class App extends StatelessWidget { | |
const App({ super.key }); | |
@override | |
Widget build(BuildContext context) { | |
return Shortcuts( | |
shortcuts: appShortcuts, | |
child: Actions( | |
actions: appActions, | |
child: FocusTraversalGroup( | |
policy: WidgetOrderTraversalPolicy(), | |
child: Builder( | |
builder: (context) => FocusScope( | |
autofocus: true, | |
child: FocusableContainer() | |
) | |
) | |
) | |
) | |
); | |
} | |
} | |
void main() { | |
runApp(const App()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment