I would link to create a TextField
that shrinks to the text inside.
To do so I used this answer that says to use an IntrinsicWidth
widget.
It works well, but if I specify a hintText
, the width of the TextField
won't be smaller than the width of the hintText
even if the user enters a very short text.
Here is an example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
alignment: Alignment.center,
height: 50,
width: 300,
child: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
color: Colors.grey[100],
child: IntrinsicWidth(
child: TextField(
decoration: InputDecoration(
hintText: 'My very very long hint', // Remove it and the text field can be as small as the text inside
),
),
),
),
),
),
),
);
}
}
Here is a text field with no hint and a small text:
The width of the text field is the width of the text inside, which is what I want. ✔️
Here is the empty field with a hint:
When there is no text, the width of the text field is the width of the hint, which is what I want. ✔️
Here is the text field with a hint a long text that the hint:
The field's width is the width of the text inside, which is what I want. ✔️
And here is a non-empty field with a hint and a small text:
As you can see the field width is the width of the hint and not the text inside (which is not what I want ❌).
How can I force it to be the width of the actual text inside?