Skip to content

Instantly share code, notes, and snippets.

@ndugger
Last active August 29, 2022 23:16
Show Gist options
  • Save ndugger/8ea45894ffc6327c2a06ea2de1200a17 to your computer and use it in GitHub Desktop.
Save ndugger/8ea45894ffc6327c2a06ea2de1200a17 to your computer and use it in GitHub Desktop.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
class App extends StatefulWidget {
final Widget root;
const App({
super.key,
required this.root
});
@override
AppState createState() {
return AppState();
}
}
class AppState extends State<App> with WidgetsBindingObserver {
final focusNode = FocusNode();
final focusScopeNode = FocusScopeNode();
final scrollController = ScrollController();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
Widget build(BuildContext context) {
return RootRestorationScope(
restorationId: null,
child: SharedAppData(
child: Shortcuts(
shortcuts: const {
SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent()
},
child: DefaultTextEditingShortcuts(
child: Actions(
actions: {
NextFocusIntent: NextFocusAction()
},
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: ShortcutRegistrar(
child: MediaQuery.fromWindow(
child: Localizations(
locale: const Locale('en'),
delegates: const [
DefaultWidgetsLocalizations.delegate
],
child: Builder(
builder: (context) {
return PrimaryScrollController(
controller: scrollController,
child: FocusScope(
node: focusScopeNode,
child: RepaintBoundary(
child: Focus(
focusNode: focusNode,
autofocus: true,
skipTraversal: true,
includeSemantics: false,
child: widget.root,
)
)
)
);
}
)
)
)
)
)
)
)
)
)
);
}
}
class FocusableContainer extends StatefulWidget {
const FocusableContainer({ super.key });
@override
FocusableContainerState createState() {
return FocusableContainerState();
}
}
class FocusableContainerState extends State {
bool hasFocus = false;
void handleFocusChange(bool focused) {
setState(() {
hasFocus = focused;
});
}
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
onFocusChange: handleFocusChange,
child: Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: hasFocus ? const Color(0xFFCC00CC) : const Color(0xFF0000FF)
),
child: const Text('focus me', style: TextStyle(color: Color(0xFFFFFFFF))),
)
);
}
}
void main() {
runApp(
App(
root: Column(
children: const [
FocusableContainer()
]
)
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment