Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic TextField width based on user input

By default, a TextField has a bottom border underneath it. The only way to control its width is by setting the width of the TextField itself (or wrapping in a Container). However, both of these involve hardcoding the width. How do I dynamically change the width of the TextField so that the underlining bottom border is only the width of the inputted text (or the hint text)?

Here are some examples.

The first image is a TextField with hint text. Its width is equal to the screen width.

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: TextField(
          decoration: InputDecoration(hintText: "Enter title"),
        ),
      ),
    );
  }

That produces the following: enter image description here

Now, I constrain the width with a Container:

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Container(
          width: 70,
          child: TextField(
            decoration: InputDecoration(hintText: "Enter title"),
          ),
        ),
      ),
    );
  }

Which produces the following:

enter image description here

When I use a container and set its width, it will never change after that. How do I have the width dynamically change based on the length of the text input?

like image 946
Ian Spryn Avatar asked Apr 11 '26 13:04

Ian Spryn


1 Answers

IntrinsicWidth(
  child: Container(
    decoration: BoxDecoration(
      border: Border(
        bottom: BorderSide(
          width: 1.0,
        ),
      ),
    ),
    child: TextFormField(),
  ),
);
like image 120
edelweisspath Avatar answered Apr 13 '26 04:04

edelweisspath