Home > Software design >  flutter textformfield counter text not updating
flutter textformfield counter text not updating

Time:07-25

I have an alert dialog in my flutter web application:

  Widget _text() {
    return TextFormField(
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.all(15),
        counterText: "$textLength",
      ),
      maxLength: maxLength,
      onChanged: (value) {
        controller.text = value;
        textLength = value.length;
        print("text length: $textLength");
        print("controller text length: ${controller.text.length}");
        setState(() {});
      },
    );
  }

and the entire alert dialog:

  showMyDialog() async {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text(
            'Share your thoughts!',
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
          content: SizedBox(
                _text(),
              ],
            ),
          ),
        );
      },
    );
  }

problem is the counter text is not updating. Can anyone point out why my counter text is not updating?

CodePudding user response:

Wrap AlertDialog with StatefulBuilder and use its setState.

 showMyDialog() async {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (context, setState) => AlertDialog(
                title: const Text(
                  'Share your thoughts!',
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                content: _text(setState)));
      },
    );
  }

And get the setState on _text method.

  Widget _text(setState) {
    return TextFormField(...);
  }
  • Related