首页 > 解决方案 > 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?

标签: flutter

解决方案


您可以将 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),
          ),
        )
      ],
    );
  }
}

推荐阅读