简体   繁体   中英

flutter textformfield counter text not updating

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?

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(...);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM