Home > front end >  Using TextEditingController live changes in Text widget
Using TextEditingController live changes in Text widget

Time:12-06

I am learning Flutter and trying now to monitor the changes on a TextEditingController. I can monitor it, using a listener function, but I cannot use the variable in a Text widget:

class _TestPageState extends State<TestPage> {
  var _textName = "";
  final _textNameController = TextEditingController();

  void _nameChanged() {
    _textName = _textNameController.text;
    print(
        "text controller changed to '${_textNameController.text}' ($_textName)");
  }

  @override
  void initState() {
    super.initState();
    _textNameController.addListener(_nameChanged);
  }

  @override
  void dispose() {
    _textNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            IconButton(
              icon: Icon(
                Icons.ac_unit,
                size: 50,
              ),
              onPressed: () => Navigator.pop(context),
            ),
            TextFormField(
              controller: _textNameController,
              // onChanged: (value) {
              //   _textName = _textNameController.text;
              // },
              decoration: InputDecoration(
                hintText: 'description',
              ),
            ),
            Text("text is ${_textName}"),
          ],
        ),
      ),
    );
  }
}

I have tried, as you can see, using a listener and changing the value of a variable, then using the variable in the Text field. Then using an onChanged function. No changes in the Text widget except when I make a change in the source code and flutter hot reloads. It seems like the Text is constant, but how?

The output strings of the listener show the correct strings, though.

How can I see live-changing the Text field, using the TextEditingController? What am I not seeing?

CodePudding user response:

You need to call setState to update the ui.

  void _nameChanged() {
    _textName = _textNameController.text;
    print(
        "text controller changed to '${_textNameController.text}' ($_textName)");

    setState(() {});
  }
  • Related