1

I would expect the effect to log the current value of the text whenever it changes, but it only runs for the initial value. Why?

class RecordForm extends HookWidget {
  final Record? record;
  const RecordForm({
    Key? key,
    this.record,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final initialTitle = record != null ? record!.title : "";
    final _title = useTextEditingController
      .fromValue(TextEditingValue(text: initialTitle));

    useEffect((){
      log.wtf(_title.value.text);
    }, [_title.value]);

    return // ...
       TextFormField(
         controller: _title,
         // ...
       ),
     // ...
     ;
  }
}
Stuck
  • 11,225
  • 11
  • 59
  • 104

1 Answers1

0

Doing it that way initializes the TextEditingController once. I think if you want to listen to real-time changes you have to add a listener to it.

TextEditingController controller = useTextEditingController();
        
        controller.addListener(() { 
          print(controller.text);
        });
Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
  • From what I know the `TextEditingController` **should** be initialized only once. But the controller is a `ValueNotifier` and I wonder why it does not notify about the changing value? Using a listener or the `onChange` field of the `TextFormField` I can achieve the desired outcome, but the question is why the value notifier does not work. – Stuck Oct 07 '21 at 21:32
  • HookWidget is basically a stateless widget so you need to trigger a rebuild by doing something like notifyListeners(). I'd have to dig in some more to figure out the technical details – Code on the Rocks Oct 07 '21 at 21:45