Change focus example to be more canonical (and correct), listening to the focus node for changes. (#35913)
This changes the example for FocusNode to be more correct, listening to the focus node for changes, instead of assuming that it is the only one doing the changing.
This commit is contained in:
parent
67ee3e191e
commit
3b945da00d
@ -236,6 +236,7 @@ class FocusAttachment {
|
||||
///
|
||||
/// class _ColorfulButtonState extends State<ColorfulButton> {
|
||||
/// FocusNode _node;
|
||||
/// bool _focused = false;
|
||||
/// FocusAttachment _nodeAttachment;
|
||||
/// Color _color = Colors.white;
|
||||
///
|
||||
@ -243,9 +244,18 @@ class FocusAttachment {
|
||||
/// void initState() {
|
||||
/// super.initState();
|
||||
/// _node = FocusNode(debugLabel: 'Button');
|
||||
/// _node.addListener(_handleFocusChange);
|
||||
/// _nodeAttachment = _node.attach(context, onKey: _handleKeyPress);
|
||||
/// }
|
||||
///
|
||||
/// void _handleFocusChange() {
|
||||
/// if (_node.hasFocus != _focused) {
|
||||
/// setState(() {
|
||||
/// _focused = _node.hasFocus;
|
||||
/// });
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// bool _handleKeyPress(FocusNode node, RawKeyEvent event) {
|
||||
/// if (event is RawKeyDownEvent) {
|
||||
/// print('Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
|
||||
@ -274,6 +284,7 @@ class FocusAttachment {
|
||||
///
|
||||
/// @override
|
||||
/// void dispose() {
|
||||
/// _node.removeListener(_handleFocusChange);
|
||||
/// // The attachment will automatically be detached in dispose().
|
||||
/// _node.dispose();
|
||||
/// super.dispose();
|
||||
@ -284,24 +295,20 @@ class FocusAttachment {
|
||||
/// _nodeAttachment.reparent();
|
||||
/// return GestureDetector(
|
||||
/// onTap: () {
|
||||
/// if (_node.hasFocus) {
|
||||
/// setState(() {
|
||||
/// if (_focused) {
|
||||
/// _node.unfocus();
|
||||
/// });
|
||||
/// } else {
|
||||
/// setState(() {
|
||||
/// _node.requestFocus();
|
||||
/// });
|
||||
/// _node.requestFocus();
|
||||
/// }
|
||||
/// },
|
||||
/// child: Center(
|
||||
/// child: Container(
|
||||
/// width: 400,
|
||||
/// height: 100,
|
||||
/// color: _node.hasFocus ? _color : Colors.white,
|
||||
/// color: _focused ? _color : Colors.white,
|
||||
/// alignment: Alignment.center,
|
||||
/// child: Text(
|
||||
/// _node.hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
|
||||
/// _focused ? "I'm in color! Press R,G,B!" : 'Press to focus'),
|
||||
/// ),
|
||||
/// ),
|
||||
/// );
|
||||
|
Loading…
x
Reference in New Issue
Block a user