4

I'm making a screen with comments section that has comments & their sub comments.

I use ScopedModel for managing state of the screen.

The data for comments is in a List<-model-> and for subcomments are inside the model->List<-model->. this data is in ScopedModel.

I build a sliverList with SliverChildBuilderDelegate so it builds only widgets that are on screen.

Every comment (current_comment) has a reply button, that, after typing, adds a comment model at the end of (current_comment)model-> List<-model-> and calls notifyListener() on the ScopedModel

Now the newly added subcomment has a tag that identifies it as a new comment.

What I want:

I want that the screen scrolls to the newly added subcomment.

What I tried:

Since the newly added subcomment can be identified by a tag, I add a GlobalKey to that comment widget when its built. and then after build is complete, I scroll to that position using the offset obtained from GlobalKey added to it.

My Problem :

Since the SliverList builds elements which are visible to screen only, the newly added comment is far below the parent comment (because reply comment button is on the parent comment only) and isn't built yet. so the builder hasn't attached the GlobalKey to it yet.

Now, how do I auto-scroll to it?

Since key isn't attached to it yet, how do I locate its position & scroll to it?

Suggest me a way to either build all elements of the Sliverlist at once so the key may be attached to the element or another strategy so to auto-scroll to the newly added comment.

James Z
  • 12,209
  • 10
  • 24
  • 44
Taosif7
  • 325
  • 1
  • 3
  • 9
  • 1
    There’s no easy direct approach to this. You’ll have to develop your own way to measure to that element’s offset for scrollTo, or you can check out https://stackoverflow.com/questions/54039684/flutter-listview-scroll-to-index-not-available and https://stackoverflow.com/questions/49153087/flutter-scrolling-to-a-widget-in-listview. https://github.com/flutter/flutter/issues/12319 has been open since 2017, but if you don’t have to use SliverList, you can try https://pub.dev/documentation/flutter_widgets/latest/flutter_widgets/ScrollablePositionedList-class.html which supports `scrollTo(index)` – TWL Nov 18 '19 at 23:08

1 Answers1

0

First solution is to set shrinkWrap property as true to the listview so it renders all children at once, and hence GlobalKey is assigned to it.

Second solution is to use a column instead, which will lead to rendering all children at once.

Both solutions are not suitable when there are too many children.

cigien
  • 57,834
  • 11
  • 73
  • 112
Taosif7
  • 325
  • 1
  • 3
  • 9