0

如何以编程方式跳转(或滚动)到条子列表中条子高度不同的特定条子?下面的代码将一本书的文本加载到自定义滚动视图中,每个小部件都有一个章节。当按下操作按钮时,我希望视图跳转到第 3 章,但没有任何反应。我究竟做错了什么?

  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);
        })
    );
  }
}
4

1 回答 1

0

对于任何发现这个问题的人,我找到了一个解决方案 - 使用 scrollablePositionedList

于 2022-01-29T15:26:36.310 回答