如何解决如何在迭代器中使用ListView
我想为时间轴构建一个ListView
的“消息卡”。消息数据来自具有多个过滤功能的Container类。我只在示例中显示一个。
编辑:澄清 我目前有一个使用ListView.builder()的ListView,这取决于能否通过索引访问源数据中的元素。
我想更改它,以便元素来自可迭代对象,该可迭代对象是在用户滚动列表视图时按需生成的。
在当前的工作解决方案中,提供程序具有一个findByChildId,它返回一个List。该列表通常很长,用户可能只想查看最近的100条左右的消息。
因此,为了不扫描成千上万的消息以返回几千条消息,我想我想使用的findByChildId会随着用户滚动而产生项目。
class MessageData with ChangeNotifier {
List<MessageRec> _messages;
// New Iterable to lazily search only for items the user wants to look at
Iterable<MessageRec> filterByChildId({String childId}) sync* {
if (childId == null) {
throw 'insanity check - Cannot search for null Child ID';
}
String previous;
if (_messages != null) {
for (MessageRec r in _messages) {
if (r.properties['thread'] == childId) {
if (previous == null || ymdFromDt(r.timeSent) != previous) {
yield DateMark.fromDateString(previous); // Special Message inserted
previous = ymdFromDt(r.timeSent);
}
yield r;
}
}
}
}
// And many other supporting methods here.
}
Note: I assume the above works - this is my first forray into Iterables in Dart / flutter.
The above used to be a method that returned a list of MessageRec by iterating over the entire list and returning all matching items.
The ListView.builder could get items from the resulting list because the elements of a List can be accessed by index.
```dart
... Timeline Widget ...
@override
Widget build(BuildContext context) {
return Consumer<MessageData>(
builder: (context,messageData,_) {
return ListView.builder((context,itemIndex) {
// How to access elements from messageData.filterByChildId(childId) here
MessageRec nextMessage = messageData.filterByChildId(childId)[itemIndex];
// The above does not work because there is no indexing on Iterables
return MessageCard.fromMessageRec(nextmessage);
}
);
}
);
}
... snip rest of Widget methods
或者答案可能在于使用带有迭代器children
的香草ListView,但我认为那还是会最终在列表中创建所有消息。
解决方法
尽管名称ListView
并不要求使用List
。您仅需要将List
与默认构造函数一起使用,但是如果您使用ListView.builder
,则可以使用Iterable
来生成值。这是一个示例:
@override
Widget build(BuildContext context) =>
ListView.builder(
itemBuilder: (BuildContext _,int i) =>
MessageCard.fromMessageRec(messageData.filterByChildId(childId).elementAt(i)
);
关于允许的项目数,ListView.builder
的文档中指出:
此构造函数适用于具有较大(或 无限)的孩子数,因为仅为生成器调用 那些实际上是可见的孩子。 引用
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。