6

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

Mohammad Amir
  • 352
  • 2
  • 12

1 Answers1

4

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),
),
Mohammad Amir
  • 352
  • 2
  • 12
  • 1
    Great solution. I'm getting error `Unhandled Exception: type 'Null' is not a subtype of type 'BuildContext'` I think may be due to stateless widget (creating keys outside build in stateless widget where context not accessible). Any idea to fix this? – Muhammad Qasim Mar 14 '22 at 11:01
  • @MuhammadQasim This is a specific issue to a part of your code but if I were to guess it's probably because of the wrong context given. Try to trace how you passed your context for the keys. Or even it might be that the context is rewritten or you removed the page or changed its context somehow. – Mohammad Amir Mar 15 '22 at 12:10
  • @MuhammadQasim Your error's reason is your widget you are want to scroll is not rendered (not in the widget tree) – Kerim Amanov May 12 '23 at 04:41