Scrolling to a TextSpan inside a RichText

Viewed 671

The problem is that I have a RichText inside a Scrollable Widget(SingleChildScrollView or ListView) and I need to Scroll to a specific TextSpan inside the RichText. Also, I cannot use ScrollablePositionedList because the texts should write in the end of the last one and if there was no space to continue the text should go to the next line so I have to use RichText. Similar to Sample Code:

ListView(
  children:[
    RichText(
      children: AListOfTextSpansThatICreateWithIndexes(),
    ),  
  ],
),

Sample Text That I want to show:

This is TextSpan1 and it is a bit 
long. This is TextSpan2 and its ok.

Similar to Scrollable position of a TextSpan within a RichText

1 Answers

There is a way to make sure a key is visible on the screen using the Scrollable.ensureVisible method. (credits to the person who deleted their comment)

you should first generate keys for your list:

var keys = List.generate(LENGTH, (i) => GlobalKey());

Then use the keys behind each TextSpan:

Text.rich(
  TextSpan(
    children: Iterable.generate(LENGTH, (i) => i)
        .expand((i) => [
              WidgetSpan(
                child: SizedBox.fromSize(
                  size: Size.zero,
                  key: keys[i],
                ),
              ),
              TextSpan(
                text: 'this is text number $i',
              ),
            ])
        .toList(),
  ),
),

Finally, call this function(where there is access to the context) to scroll to the desired key:

Scrollable.ensureVisible(
   keys[i].currentContext,
   alignment: 0.2,
   duration: Duration(milliseconds: 500),
),
Related