[英]Efficient storage fetching for ListView.builder, GridView.builder
In order to fetch data from the API with the builder function of ListView.builder
or GridView.builder
you have to create a list of Widgets that is being filled when you scroll.为了使用
ListView.builder
或GridView.builder
的构建器 function 从 API 获取数据,您必须创建滚动时正在填充的小部件列表。
The actual reason for using the Builder function is, to deal with large Lists so that only widgets are being rendered/build when needed:使用 Builder function 的实际原因是,处理大型列表,以便在需要时仅渲染/构建小部件:
List<Widget> _mediaList = [];
int currentPage = 0;
int? lastPage;
@override
void initState() {
super.initState();
_fetchNewMedia();
}
_handleScrollEvent(ScrollNotification scroll) {
if (scroll.metrics.pixels / scroll.metrics.maxScrollExtent > 0.33) {
if (currentPage != lastPage) {
_fetchNewMedia();
}
}
}
_fetchNewMedia() async {
lastPage = currentPage;
setState(() {
_mediaList.add(
Text("Some Widget"),
);
currentPage++;
});
}
@override
Widget build(BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scroll) {
_handleScrollEvent(scroll);
return false;
},
child: GridView.builder(
controller: widget.scrollCtr,
itemCount: _mediaList.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return _mediaList[index];
}),
);
}
The problem that I see is, that if you have an endless list (like a Post feed), that the list would store every Data source and the list would eventually jam up the RAM.我看到的问题是,如果您有一个无穷无尽的列表(如 Post 提要),该列表将存储每个数据源,并且该列表最终会堵塞 RAM。
I would imagine that you either have to clear the list after scrolling for a long time or you would need to only store String-IDs and load the data according to them.我想您要么必须在滚动很长时间后清除列表,要么只需要存储字符串 ID 并根据它们加载数据。
Is that concern appropriate or does the builder also optimize the storage in that case?这种担忧是否合适,或者在这种情况下,构建器是否也优化了存储?
You should store String-IDs and build the list items using
FutureBuilder()
.您应该存储 String-ID 并使用
FutureBuilder()
构建列表项。 Because althoughListView.builder()
renders only those items which are visible on the device screen but in case of post feed the post data may consume so much storage which can cause efficiency problem.因为虽然
ListView.builder()
只渲染那些在设备屏幕上可见的项目,但是在 post feed 的情况下,post 数据可能会消耗太多的存储空间,从而导致效率问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.