TextEditingController vs OnChanged

前端 未结 2 574
[愿得一人]
[愿得一人] 2021-02-13 03:28

I am looking for a better explanation on the benefit of TextEditingController over OnChanged event for a TextField.

My understanding is that onChanged\'s setState notifi

2条回答
  •  时光说笑
    2021-02-13 04:24

    TextEditingController actually is managing his own state, that's why you can see the input on the screen once you change it.

    You have 2 problems here, the first is that you are not adding any listener to the TextEditingController, you are just asking "give me the current value" only when you build the widget, not "give me the value any time it changes". To achieve this you need to add a listener to the text controller and it will be called every time that the value change.

    Try this :

      @override
      void initState() {
        super.initState();
        // Start listening to changes.
        ctrl.addListener(_printValue);
      }
    
      _printValue() {
        print("Value: ${ctrl.text}");
      }
    

    This will work because print doesn't need to render anything on the screen but if you change it to return a widget it will not work either. That is the second problem, as you pointed out, your parent widget is not been rebuild when the value change, in this case you cannot avoid the setState (or other way to tell flutter that needs to rebuild the widget) when the value change because you need to rebuild the widget to view the change.

    Another thing that ill like to point out is that TextEditingController is much powerful and it can be used for more things that just add notifiers to changes. For example if you want a button on other part of the screen that clear the text on a TextField you will need a TextEditingController binded to that field.

    Hope it helps!

提交回复
热议问题