我正在尝试绑定一个快捷方式(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,
);
}
}
我相信你可以尝试使用类似于dispose 的东西
void setFocus() {
focusNode.requestFocus();
}
@override
void dispose() {
// TODO: implement dispose
focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {...