flutter - tapping prefixIcon of TextField causes TextField to be focussed
问题描述
I have a TextField which has an attribute prefixIcon that accepts a widget. I passed a GestureDetector so that I can do something onTap event of it. But the problem I am facing is as soon as I tap it, though it calls onTap event it but along with that it also focussed the TextField that further launches the keyboard.
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body:MyWidget,
);
}
}
class MyWidget extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return MyWidgetState();
}
}
class MyWidgetState extends State<MyWidget>
{
@override
Widget build(BuildContext context) {
return Container(
height: 200,
width: 200,
padding: EdgeInsets.all(20),
child: TextField(
decoration: InputDecoration(
prefixIcon: GestureDetector(
child: Container(color: Colors.greenAccent, width: 25, height: 25,),
onTap: () => print("hmm"),
),
),
),
);
}
}
So I am trying to find a way by which tapping on prefixIcon widget (here GestureDetector doesn't focus TextField). How can I achieve that functionality?
解决方案
您可以将 TextField 包装在一个 Row 中,然后在该图标之前添加一个可点击的图标。那么默认行为是什么并不重要。
Container(
height: 200,
width: 200,
padding: EdgeInsets.all(20),
child: Row(
children: <Widget>[
GestureDetector(
child: Container(color: Colors.greenAccent, width: 25, height: 25,),
onTap: () => print("hmm"),
),
Expanded(child: TextField()),
],
),
)
我想我有一个更好的解决方案给你,因为它不需要对 FocusNode 进行任何操作。只需将两者传递到堆栈中,使用 CompositedTransformTarget/Followers 并用您想要的项目覆盖装饰器。我已经对其进行了测试,并且可以正常工作。它还使您想要放置在前缀输入上的图标跟随文本字段的大小(如果这是您想要的)。保持同步。
class TestWidget extends StatelessWidget {
final LayerLink link = LayerLink();
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
TextField(
maxLines: null,
decoration: InputDecoration(
prefixIcon: CompositedTransformTarget(
child: Container(color: Colors.transparent, width: 25, height: 25,),
link: link,
),
)
),
CompositedTransformFollower(
link: link,
child: GestureDetector(
child: Container(color: Colors.greenAccent, width: 25, height: 25,),
onTap: () => Vibrate.feedback(FeedbackType.heavy),
),
)
],
);
}
}
推荐阅读
- amazon-web-services - 通过 SNS 和 Lambda 的电子邮件通知
- git - 使用 ARM 模板 C# 将私有 git 存储库部署到 Azure 应用服务时出错
- java - 如何将正则表达式匹配到字符和某些符号的任意组合,除了'% 和 %' 之间的一行中的两个破折号
- java - 如果由于 CMS gc 算法中的关键内存碎片而无法分配内存会发生什么
- neo4j - 将现有数据库导入 Neo4j 桌面应用程序 (v1.1.9)
- oauth - 加密的自定义字段是存储 Apex 标注的有限生命周期 OAuth 令牌的安全方式吗?
- jquery - 如何在jquery中将动态创建的字段设为必填字段
- dsl - 如何使用空手道 dsl 读取 CDATA 元素
- python - 如何从 Python 中的列表中生成所有可能的数字排列?
- c - Clang -Wconditional-uninitialized on struct member array assignment