Skip to content

Instantly share code, notes, and snippets.

@mingsai
Last active May 27, 2020 21:48
Show Gist options
  • Save mingsai/6cc3ab020813efa7c9c337fa14a14894 to your computer and use it in GitHub Desktop.
Save mingsai/6cc3ab020813efa7c9c337fa14a14894 to your computer and use it in GitHub Desktop.
Flutter Autogrowth TextField
class _MyScreenState extends State<MyScreen> {
double _inputHeight = 50;
final TextEditingController _textEditingController = TextEditingController();
@override
void initState() {
super.initState();
_textEditingController.addListener(_checkInputHeight);
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
void _checkInputHeight() async {
int count = _textEditingController.text.split('\n').length;
if (count == 0 && _inputHeight == 50.0) {
return;
}
if (count <= 5) { // use a maximum height of 6 rows
// height values can be adapted based on the font size
var newHeight = count == 0 ? 50.0 : 28.0 + (count * 18.0);
setState(() {
_inputHeight = newHeight;
});
}
}
// ... build method here
TextField(
controller: _textEditingController,
textInputAction: TextInputAction.newline,
keyboardType: TextInputType.multiline,
maxLines: null,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment