I’m currently facing an issue with scrolling text selection in a TextFormField
. I have a custom TextAreaFormField
widget with a fixed height and a ScrollView
for handling longer texts. However, when I select and move the text, the selection can go outside the text field’s border and become hidden.
The issue arises when I select and move the text within the TextFormField. The text selection can go out of the visible area, and I need the TextFormField to scroll appropriately to keep the selected text within the visible region.
How to make the TextFormField
scroll when selecting and moving text, so that the selected text remains within the visible area? Any guidance or code examples would be greatly appreciated. Thank you!
Here’s my code:
class _CustomTextAreaFormFieldContent extends StatefulWidget {
final String? value;
final ValueChanged<String> onChanged;
final EdgeInsets scrollPadding;
final double? height;
final bool readOnly;
const _CustomTextAreaFormFieldContent({
required this.value,
required this.onChanged,
required this.scrollPadding,
required this.height,
this.readOnly = false,
Key? key,
}) : super(key: key);
@override
_CustomTextAreaFormFieldContentState createState() =>
_CustomTextAreaFormFieldContentState();
}
class _CustomTextAreaFormFieldContentState
extends State<_CustomTextAreaFormFieldContent> {
final _scrollController = ScrollController();
final _textController = TextEditingController();
@override
void initState() {
super.initState();
_textController.text = widget.value ?? '';
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 12,
),
const Div(),
Scrollbar(
controller: _scrollController,
thumbVisibility: true,
child: SizedBox(
height: widget.height == null ? null : widget.height! - 121,
child: SingleChildScrollView(
controller: _scrollController,
child: Column(
children: [
const SizedBox(
height: 16,
),
TextFormField(
controller: _textController,
style: Theme.of(context).textTheme.bodyLarge,
scrollPadding: widget.scrollPadding,
decoration: const InputDecoration.collapsed(
hintText: '',
),
readOnly: widget.readOnly,
onChanged: (value) => widget.onChanged(
value.trim(),
),
minLines: 6,
maxLines: null,
keyboardType: TextInputType.multiline,
),
],
),
),
),
),
],
);
}
}
2
Answers
To address the issue of scrolling the TextFormField’s content while maintaining text selection visibility, you’ll need to update the scroll position in sync with the text selection changes.
Here is my Main.dart file code i have used TextField
main.dart