Last active
May 27, 2020 21:48
-
-
Save mingsai/6cc3ab020813efa7c9c337fa14a14894 to your computer and use it in GitHub Desktop.
Flutter Autogrowth TextField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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