Home > Mobile >  How to get the height of TextField in Flutter
How to get the height of TextField in Flutter

Time:10-05

I would like to measure the current height of a text field. The text field will of course get bigger when new words are added. The problem is that MeasureSize is not triggered by this. How can I get the height of the widget every time onChanged is triggered?

MeasureSize(
  onChange: (size) {
    print('size: ${size.height}');
  },
  child: TextField(
    keyboardType: TextInputType.multiline,
    maxLength: null,
    maxLines: null,
    minLines: 5,
    autofocus: true,
    controller: widget.storyController,
    onChanged: (text) {
      _dreamEditorUsecase.updateStory(text);
      widget.onStoryChanged(text);
    },
  ),
);

CodePudding user response:

You can use StatefulWidget:

class MeasureTextField extends StatefulWidget {
  const MeasureTextField({super.key});

  @override
  State<MeasureTextField> createState() => _MeasureTextFieldState();
}

class _MeasureTextFieldState extends State<MeasureTextField> {
  @override
  Widget build(BuildContext context) {
    return MeasureSize(
      onChange: (size) {
        print('size: ${size.height}');
      },
      child: TextField(
        keyboardType: TextInputType.multiline,
        maxLength: null,
        maxLines: null,
        minLines: 5,
        autofocus: true,
        controller: widget.storyController,
        onChanged: (text) {
          setState(() {
            _dreamEditorUsecase.updateStory(text);
            widget.onStoryChanged(text);
          });
        },
      ),
    );
  }
}

each time it change it will rebuild and print what you like

  • Related