'Scrollable SelectableText when selecting text from bottom autoscrolls to top of widget

enter image description here

As shown above when selecting text from a scrollable SelectableText Widget it auto scrolls to top initially. Expected behavior is scroll remains in the bottom when text is selected.

I have tried all answers on stackoverflow but it seems this is flutter bug, but if anyone has workaround for it now than it would be great!

You can find code in this github repo.



Solution 1:[1]

I found a short ugly workaround.

Seems that selectable text tries to be sure the cursor/selected text is seen, by jumping to its text field. In this case when the text field is so big, it jumps to the beginning.

Since in my app I only have long selectable text, without the need to edit it in shorter text fields, I just commented the line that calls jumping when text is selected.

The Workaround:

In file: flutter/packages/flutter/lib/src/widgets/editable_text.dart

In function: userUpdateTextEditingValue

Comment out the line that calls to: _scheduleShowCaretOnScreen

Like this:

  @override
void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause? cause) {
    // Compare the current TextEditingValue with the pre-format new
    // TextEditingValue value, in case the formatter would reject the change.
    final bool shouldShowCaret = widget.readOnly
      ? _value.selection != value.selection
      : _value != value;
    if (shouldShowCaret) {
      // _scheduleShowCaretOnScreen(); --> This line causes the problem
    }
    _formatAndSetValue(value, cause, userInteraction: true);
  }

Solution 2:[2]

With this merged pull request the issue shall be gone on next flutter release.

Until this release you can add following workaround on SelectableText.rich which is not as fluent as the real fix:

onSelectionChanged: (selection, cause) {
  Future.delayed(const Duration(milliseconds: 10), () {
   _scrollController.jumpTo(_scrollController.offset);
  });
},

Solution 3:[3]

I am having the same problem. I set the selectionHeightStyle parameter to BoxHeightStyle.includeLineSpacingMiddle and the problem was solved. I found a solution like this:

SelectableText(
        'sample long text...',
        selectionHeightStyle: BoxHeightStyle.includeLineSpacingMiddle,
        
      );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johanna
Solution 2 Ramazan Gevrek
Solution 3 Dada