问题
Is there any way to detect a tap outside of TextTield? I wanna make a self sufficient search field component which should expend when focused and shrink when a focus is lost. The TextField is using FocusNode to unfocus itself when the focus is not needed but the problem is that I can't get the way to detect a tap outside of it. Wrapping the whole app in GestureDetector and requesting a new focus on tap is not an option at all because, first this tap can be easily intercepted by any component containing their own gesture detectors, second it will make my component not self sufficient and I'll have to write some extra code outside of it, which is not preferable
here is the code of my search field for the moment
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(_padding),
child: AnimatedContainer(
decoration: BoxDecoration(
border: Border.all(color: Colors.black12, width: 2),
borderRadius: BorderRadius.all(Radius.circular(6)),
color: pizzaWhite,
),
height: 40,
width: !_isExpanded
? MediaQuery.of(context).size.width / 2 - (_padding * 2)
: MediaQuery.of(context).size.width - (_padding * 2),
child: Padding(
padding: const EdgeInsets.only(left: _padding, right: _padding),
child: Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: RawKeyboardListener(
focusNode: _keyboardFocusNode,
onKey: (RawKeyEvent e) {
},
child: TextField(
keyboardType: TextInputType.text,
onEditingComplete: _sendSearch,
controller: _controller,
focusNode: _textFocusNode,
cursorColor: pizzaBottomBarColor,
onTap: () => _switchExpanded(true),
decoration: InputDecoration(
alignLabelWithHint: true,
contentPadding: EdgeInsets.only(top: 1),
border: InputBorder.none,
hintText: 'Search...'
),
style: TextStyle(
fontSize: 18,
fontFamily: 'OpenSans',
fontWeight: FontWeight.w100,
),
),
),
),
GestureDetector(
onTap: () => _switchExpanded(false),
child: Icon(
Icons.search
),
),
],
),
),
duration: Duration(milliseconds: 250),
curve: Curves.fastOutSlowIn,
),
)
],
);
}
回答1:
I've removed the solution code from here (as it's outdated) and added my pub repository which contains the most recent solution
https://pub.dev/packages/flutter_focus_watcher
You can also filnd it on my github
https://github.com/caseyryan/flutter_focus_watcher
回答2:
you need to separate from the other widgets and wrap them in GestureDetector
and call it's onTap | onTapDown
来源:https://stackoverflow.com/questions/57842100/flutter-a-way-for-textfield-to-detect-tap-outside