Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter update countertext

Tags:

flutter

In Flutter, inputDecoration's countertext property does not change as the user is typing in the TextFormField. Is it possible to decrement the countertext as the user is typing?

TextFormField(
 keyboardType: TextInputType.number,
 decoration: new InputDecoration(
   counterText: "9",
   hintText: "Enter exact order number",
  ),
)
like image 514
user2408073 Avatar asked Jun 07 '26 02:06

user2408073


2 Answers

I do not recommend using the decoration: InputDecoration::counterText. You have to use setState or whatever to manually update the counter that way.

Instead, I recommend the maxLength property, that automatically makes a counter and updates it:

TextField(maxLength: 8)

Result:

enter image description here

This might be what most people want.

You can even further customize it with the buildCounter parameter, to return whatever widget you want when the text length changes. For example, if you only want to display how many characters left, you can do this:

TextField(
  maxLength: 8,
  buildCounter: (
    BuildContext context, {
    int currentLength,
    int maxLength,
    bool isFocused,
  }) {
    return Text('${maxLength - currentLength}');
  },
)

enter image description here

like image 140
user1032613 Avatar answered Jun 08 '26 22:06

user1032613


I edit this answer to work with your question

class StackEditText extends StatefulWidget {
  @override
  _StackEditTextState createState() => _StackEditTextState();
}

class _StackEditTextState extends State<StackEditText> {

  TextEditingController _controller = new TextEditingController();

  void onValueChange() {
      setState(() {
        _controller.text;
      });
  }

  @override
  void initState() {
    super.initState();
    _controller.addListener(onValueChange);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: TextFormField(
          controller: _controller,
          maxLength: 9,
          decoration: InputDecoration(
            counterText: "${9 - _controller.text.length}",
            hintText: 'Enter exact order number',
          ),
        ),
      ),
    );
  }
}
like image 44
Ahmed Avatar answered Jun 09 '26 00:06

Ahmed