Flutter Windows TextField 通过快捷键绑定设置焦点

发布于 2025-01-13 11:20:19 字数 3126 浏览 3 评论 0原文

我正在尝试绑定快捷键(ctrl + f)来设置焦点文本字段。到目前为止,它只能工作一次,因此在我按 ctrl + f 后,文本字段将获得焦点,但是当文本字段失去焦点时(因为我(故意)单击屏幕上的其他位置)并再次尝试快捷方式,它不起作用。使用简单的计数器可以工作,但不能使用文本字段,所以我认为问题是由于文本字段的 focusNode 引起的,但我不知道如何使其正常工作...

这是一个最小的可重现代码示例:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  FocusNode focusNode = FocusNode();

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void setFocus() {
    focusNode.requestFocus();
  }


  @override
  Widget build(BuildContext context) {
    return CounterShortcuts(
        onIncrementDetected: _incrementCounter,
        onFocusDetected: setFocus,
        child: Scaffold(
        appBar: AppBar(
        title: Text(widget.title),
    ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have clicked the arrow up key this many times:',
            ),
            // a simple counter test which works always
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            // a textfield test which does not work after unfocusing
            TextField(
              focusNode: focusNode,
            )
          ],
        ),
      ),
    ));
  }
}
// for the counter test
final incrementKeySet = LogicalKeySet(
  LogicalKeyboardKey.control,
  LogicalKeyboardKey.arrowUp,
);
// for the textfield
final focusKeySet = LogicalKeySet(
  LogicalKeyboardKey.control,
  LogicalKeyboardKey.keyF,
);

class IncrementIntent extends Intent {}
class FocusIntent extends Intent {}

class CounterShortcuts extends StatelessWidget {

  final Widget child;
  final VoidCallback onIncrementDetected;
  final VoidCallback onFocusDetected;

  const CounterShortcuts({
    Key? key,
    required this.child,
    required this.onIncrementDetected,
    required this.onFocusDetected,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FocusableActionDetector(
      autofocus: true,
      shortcuts: {
        incrementKeySet: IncrementIntent(),
        focusKeySet: FocusIntent(),
      },
      actions: {
        IncrementIntent:
        CallbackAction(onInvoke: (e) => onIncrementDetected.call()),
        FocusIntent:
        CallbackAction(onInvoke: (e) => onFocusDetected.call()),
      },
      child: child,
    );
  }
}

I am trying to bind a shortcut (ctrl + f) to set a textfield in focus. So far it only works once, so after I press ctrl + f the textfield is focussed, but when the textfield loses focus (because I click somewhere else on the screen (intentionally)) and try the shortcut again, it doesn't work. With a simple counter it works, but not with the textfield, so I suppose the problem occurs due to the focusNode of the TextField, but I don't know how to make it work properly...

Here is a minimal reproducible code sample:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  FocusNode focusNode = FocusNode();

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void setFocus() {
    focusNode.requestFocus();
  }


  @override
  Widget build(BuildContext context) {
    return CounterShortcuts(
        onIncrementDetected: _incrementCounter,
        onFocusDetected: setFocus,
        child: Scaffold(
        appBar: AppBar(
        title: Text(widget.title),
    ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have clicked the arrow up key this many times:',
            ),
            // a simple counter test which works always
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            // a textfield test which does not work after unfocusing
            TextField(
              focusNode: focusNode,
            )
          ],
        ),
      ),
    ));
  }
}
// for the counter test
final incrementKeySet = LogicalKeySet(
  LogicalKeyboardKey.control,
  LogicalKeyboardKey.arrowUp,
);
// for the textfield
final focusKeySet = LogicalKeySet(
  LogicalKeyboardKey.control,
  LogicalKeyboardKey.keyF,
);

class IncrementIntent extends Intent {}
class FocusIntent extends Intent {}

class CounterShortcuts extends StatelessWidget {

  final Widget child;
  final VoidCallback onIncrementDetected;
  final VoidCallback onFocusDetected;

  const CounterShortcuts({
    Key? key,
    required this.child,
    required this.onIncrementDetected,
    required this.onFocusDetected,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FocusableActionDetector(
      autofocus: true,
      shortcuts: {
        incrementKeySet: IncrementIntent(),
        focusKeySet: FocusIntent(),
      },
      actions: {
        IncrementIntent:
        CallbackAction(onInvoke: (e) => onIncrementDetected.call()),
        FocusIntent:
        CallbackAction(onInvoke: (e) => onFocusDetected.call()),
      },
      child: child,
    );
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空 2025-01-20 11:20:19

我相信你可以尝试使用类似 dispose 的东西

void setFocus() {
  focusNode.requestFocus();
}

@override
void dispose() {
  // TODO: implement dispose
  focusNode.dispose();
  super.dispose();
}

@override
Widget build(BuildContext context) {...

I believe you can try to use something like the dispose

void setFocus() {
  focusNode.requestFocus();
}

@override
void dispose() {
  // TODO: implement dispose
  focusNode.dispose();
  super.dispose();
}

@override
Widget build(BuildContext context) {...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文