跳转到 flutter sliverlist 中的特定条子
Jumping to a particular sliver in a flutter sliverlist
如何以编程方式跳转(或滚动)到条子列表中的特定条子,其中条子列表的高度各不相同?下面的代码将一本书的文本加载到自定义滚动视图中,每个小部件都有一个章节。当按下操作按钮时,我希望视图跳转到第 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);
})
);
}
}
对于发现此问题的任何人,我已经找到了解决方案 - 使用
scrollablePositionedList
如何以编程方式跳转(或滚动)到条子列表中的特定条子,其中条子列表的高度各不相同?下面的代码将一本书的文本加载到自定义滚动视图中,每个小部件都有一个章节。当按下操作按钮时,我希望视图跳转到第 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);
})
);
}
}
对于发现此问题的任何人,我已经找到了解决方案 - 使用 scrollablePositionedList