BigPictureDeepDive
BigPictureDeepDive

Reputation: 211

Flutter: Position MaxLength Counter INSIDE of TextField

Is there a way to position the character counter inside the text field in Flutter? I found someone else's question asking about a custom counter and managed to put that in place, but it is still below the field and outside of the field. I would love to place it where the suffix goes but I bet that's not possible. Is there another way to make the counter appear inside the field?

Thanks in advance!

Upvotes: 7

Views: 5066

Answers (1)

Apb
Apb

Reputation: 819

Get the length of the text and then change the suffix text to equal that length.

Like this

class MyTextField extends StatefulWidget {
  @override
  _MyTextFieldState createState() => _MyTextFieldState();
}

class _MyTextFieldState extends State<MyTextField> {
  var maxLength = 10;
  var textLength = 0;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        contentPadding: EdgeInsets.all(15),
        suffixText: '${textLength.toString()}/${maxLength.toString()}',
        counterText: "",
      ),
      cursorRadius: Radius.circular(10),
      keyboardType: TextInputType.text,
      autofocus: true,
      maxLength: maxLength,
      onChanged: (value) {
        setState(() {
          textLength = value.length;
        });
      },
    );
  }
} 

Upvotes: 11

Related Questions