我对Flutter很陌生。我正在开发一个应用程序,当用户导航到ListView或从ListView导航时,该应用程序需要保留ListView中的滚动位置。我正在尝试使用ScrollablePositionedList完成此操作。我已遵循Google提供的简单示例,并且在我的jumpTo
上调用ItemScrollController
时遇到错误。
我的ListView是从下载的JSON构建的,因此我正在使用FutureBuilder来初始构建和缓存列表视图项模型。
这是我的代码的摘录:
var listener = ItemPositionsListener.create();
var scroller = ItemScrollController();
ScrollablePositionedList _listView(
AsyncSnapshot snapshot, BuildContext context) {
var list = ScrollablePositionedList.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index].gaugeName),
);
},
itemPositionsListener: listener,
itemScrollController: scroller,
);
scroller.jumpTo(index: 100); // error here
return list;
}
@override
Widget build(BuildContext context) {
_getFavorites();
return Scaffold(
appBar: AppBar(
title: Text(kAllStates[widget.stateAbbreviation]),
),
body: FutureBuilder(
future: _getGaugesForState(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return _listView(snapshot, context);
} else {
return Align(child: CircularProgressIndicator());
}
},
),
endDrawer: RFDrawer(),
);
}
}
调用scroller.jumpTo(index: 100);
时,出现以下错误:
NoSuchMethodError: The method '_jumpTo' was called on null.
Receiver: null
有人对导致此错误的原因有什么线索,或者在这里我可能做错了什么?
谢谢!
答案 0 :(得分:0)
我不确定是否可以纠正我的错误,但是您有信心从API中获得100项吗?所以我想您正在跳到一个不存在的索引。另一个猜测是您正在尝试在构建ListView之前跳到索引,因此我想您可以返回列表,然后在经过一段时间后使用按钮滚动到特定索引或使用Timer对象自动滚动确保ListView完全构建。
另外,如果您想在导航到不同页面时保留滚动偏移量或位置,例如您的导航栏具有不同的选项卡,其中之一具有ListView,并且您想在导航时保留滚动位置,所以我假设PageStorageKey是一个不错的选择。