Created
September 3, 2022 18:01
-
-
Save ndugger/7310b7d4a381f7226198e5d6b38ab71f to your computer and use it in GitHub Desktop.
Flutter Focus Orchestration - Runnable 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 StatefulWidget { | |
const FocusableContainer({ super.key }); | |
@override | |
FocusableContainerState createState() { | |
return FocusableContainerState(); | |
} | |
} | |
class FocusableContainerState extends State { | |
bool isFocused = false; | |
void handleFocusChange(bool focused) { | |
setState(() { | |
isFocused = focused; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Focus( | |
onFocusChange: handleFocusChange, | |
child: Container( | |
width: 100, | |
height: 100, | |
decoration: BoxDecoration( | |
color: isFocused ? const Color(0xFF0000FF) : const Color(0xFF00FF00) | |
) | |
) | |
); | |
} | |
} | |
class App extends StatelessWidget { | |
const App({ super.key }); | |
@override | |
Widget build(BuildContext context) { | |
return Directionality( | |
textDirection: TextDirection.ltr, | |
child: Shortcuts( | |
shortcuts: appShortcuts, | |
child: Actions( | |
actions: appActions, | |
child: FocusTraversalGroup( | |
policy: WidgetOrderTraversalPolicy(), | |
child: Builder( | |
builder: (context) => FocusScope( | |
autofocus: true, | |
child: Builder( | |
builder: (context) => Focus( | |
child: Flex( | |
direction: Axis.horizontal, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: const [ | |
FocusableContainer(), | |
FocusableContainer(), | |
FocusableContainer() | |
] | |
) | |
) | |
) | |
) | |
) | |
) | |
) | |
) | |
); | |
} | |
} | |
void main() { | |
runApp(const App()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment