Flutter TextEditingController监听器调用次数过多

时间:2018-05-24 02:03:57

标签: android ios dart textfield flutter

好的,所以我有一个带有textfield的屏幕,它有一个textEditingController,一个侦听器在init状态下添加一次。监听器功能推送一个新屏幕,然后当我弹出这个屏幕时,立即再次调用监听器功能,除非我在按下屏幕后立即删除监听器。我要么想弄清楚如何防止调用侦听器函数,要么区分对侦听器函数的调用不仅仅来自用户单击文本字段。我猜第二种选择是正确的,但是我很吵,所以我对如何做到这一点毫无头绪。谢谢你们!!

Heres是我的代码的基本概述....

SCREEN 1

class SubmitPost extends StatefulWidget{

  _submitPostState createState() => new _submitPostState();

}



class _submitPostState extends State<SubmitPost>{

final originTextContoller = new TextEditingController();

 void initState() {
    super.initState();

originTextContoller.addListener(_onOriginTouch);



   }


_onOriginTouch() {


    // my guess is that I need some type of conditional statement to determine wheter or not this function was triggered by the user or the "notifyAllListeners" function which is getting called for some reason. I think that's what's happening but idk...



    Navigator.push(context, new MaterialPageRoute(builder: (context) => new PlacePicker()));


}



  @override
  void dispose() {
    // Clean up the controller when the Widget is removed from the Widget tree

     originTextContoller.removeListener(_onOriginTouch);
    originTextContoller.dispose();

    super.dispose();
  }


}

SCREEN 2

class PlacePicker extends StatefulWidget {

   @override
  _PickerState createState() => new _PickerState();
}

class _PickerState extends State<PlacePicker> {

 // basically just a list view with on tap meathod below



    onTap: () async {  // async needed for separate function not called now

      Navigator.pop(context);

}



}

1 个答案:

答案 0 :(得分:0)

TextField 的 eventListener 被触发的原因是因为它专注于弹出第二个屏幕以返回到第一个屏幕。您可能需要考虑将 Navigator 放在 Button 而不是监听器上。