TextEditingController vs OnChanged

前端 未结 2 576
[愿得一人]
[愿得一人] 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:09

    That's not false. You are just not setting state synchronously that's all. What onChanged does is exactly possible with this approach:

    class _TestFormState extends State {
      TextEditingController controller;
    
      @override
      void initState() {
        controller = TextEditingController();
        controller.addListener(() {
          setState(() {});
        });
        super.initState();
      }
    
      @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text('Current Value: ${controller.text}'),
            TextField(
              controller: controller,
            ),
          ],
        );
      }
    }
    

    As you see, we have listener that setting state everytime the controller state changes. This is exactly what onChanged does.

    Edit: So, about benefits, you can achieve everything with both approach, it's a subjective way. But there are things matters:

    1 - If you have BLoC pattern, you can directly assign your Stream with onChanged method.

    2 - With TextEditingController you can use same controller in many place. You can achieve same thing with onChanged but it will look like workaround when someone reads your code it will look like broken code :)

    3 - onChanged method is also very viable for RegEx assertion etc. It will look much cleaner comparing the controller.

    At the end in my opinion, onChanged better for modularity and cleaner code in most cases. As I said it's all up to you, that's all come up my mind for now.

提交回复
热议问题