Home > Software engineering >  How to listen to TextField changes realtime and update a Text widget with TextField content?
How to listen to TextField changes realtime and update a Text widget with TextField content?

Time:07-23

I have a TextField and a Text widget that should show in RealTime the text written in the TextField.

This is the code:

 late final TextEditingController _importo;

  @override
  void initState() {
    _importo = TextEditingController();
    super.initState();

    @override
    Widget build(BuildContext context) {
      return Column(children: [
        SizedBox(
          width: 50,
          child: TextField(
            textAlign: TextAlign.end,
            controller: _importo,
            decoration: const InputDecoration(
              hintText: '0.00',
            ),
            autocorrect: false,
            keyboardType: TextInputType.number,
          ),
        ),
        Text(
          _importo.text,
          style: const TextStyle(
            fontWeight: FontWeight.w400,
            fontSize: 15,
          ),
        ),
      ]);
    }
  }

I think there is something missing because the Text widget isn't updating.

CodePudding user response:

There is scope(brackaet) issue on your code on initState and text will auto update on textField and adding listener update others UI widget on text changes.

 late final TextEditingController _importo;

 @override
  void initState() {
    super.initState();
    _importo = TextEditingController()
      ..addListener(() {
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      SizedBox(
        width: 50,
        child: TextField(
          textAlign: TextAlign.end,
          controller: _importo,
          decoration: const InputDecoration(
            hintText: '0.00',
          ),
          autocorrect: false,
          keyboardType: TextInputType.number,
        ),
      ),
      Text(
        _importo.text,
        style: const TextStyle(
          fontWeight: FontWeight.w400,
          fontSize: 15,
        ),
      ),
    ]);
  }
}

CodePudding user response:

In text field in change event set state

TextField (
 onChanged:(val){
   setState((){});
  }
)
  • Related