Jumping to a particular sliver in a flutter sliverlist

Issue

How can I programmatically jump (or scroll) to a particular sliver in a sliver list where the slivers vary in height? The code below loads the text of a book into a custom scroll view, with a chapter for each widget. When the action button is pressed I want the view to jump to chapter 3, but nothing happens. What am I doing wrong?

  class BookPage extends StatefulWidget {
  BookPage({Key? key, this.title = "book"})  : super(key: key);
  String title;
  final _chapter3key = new GlobalKey(debugLabel: "chap3key");

  get chapter3Key => _chapter3key;

  @override
  _BookState createState() => _BookState();
}

class _BookState extends State<BookPage> {
  ScrollController? scrollController = new ScrollController();
  Map<int, String> chapterHTML = {};
  String title = "";
  final chapterCount=10;

  void fetchText() async {
    for (int i = 1; i <= 10; i++) {
      chapterHTML[i] = await getChapterHtml(i);
    }
    setState(() {});
  }

  _BookState() {
    fetchText();
  }

  Widget chapterSliver(int i) {
    if (i==3) {
      return Html(key: widget.chapter3Key, data: chapterHTML[i] ?? "", );
    }
    return Html(
      data: chapterHTML[i] ?? "",
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: CustomScrollView(controller: scrollController, slivers: [
          SliverList(
              delegate: SliverChildBuilderDelegate ((BuildContext context, int index) {
                  if (index > chapterCount) return null;
                  return chapterSliver(index);
                }// first sliver is empty (chapter 0!)
              ))
        ]),
        floatingActionButton: FloatingActionButton(onPressed: () {
          Scrollable.ensureVisible(widget.chapter3Key.currentContext);
        })
    );
  }
}

Solution

For anyone finding this question, I’ve found a solution – use a
scrollablePositionedList

Answered By – Frank H

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.