我想每四个项目显示一个带有listView.builder的特殊小部件。
我得到了这两个 list
List<Event> events = [];
List<SpecialEvent> specialEvent = [];
这些列表由两个Streambuilder填充,如下所示
StreamBuilder(
stream: stream,
builder: (BuildContext context,
AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
if (!snapshot.hasData) {
//Spinner
}
events = snapshot.data.map((doc) => Event.fromDocument(doc)).toList();
if (events.isEmpty) {
//Code here
}
return StreamBuilder(
stream: stream,
builder: (BuildContext context,
AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
if (!snapshot.hasData) {
//Spinner
}
specialEvents = snapshot.data
.map((doc) => specialEvents.fromDocument(doc))
.toList();
eventCount = 0;
specialEventCount = 0;
return Flexible(
child: ListView.builder(
itemCount: events.length + specialEvents.length,
itemBuilder: (context, index) {
int newIndex = index + 1;
if (index != 0 &&
newIndex % 4 == 0 &&
specialEventCount.length > specialEventCount ||
specialEventCount.length > specialEventCount &&
events.length <= eventCount) {
specialEventCount += 1;
return buildSpecialEvent(specialEventCount - 1);
} else if (events.length > eventCount) {
eventCount += 1;
return buildEvent(eventCount - 1);
} else {
return Text("");
}
},
),
);
});
},
);
当涉及初始列表 View 构建时,此代码非常有效。
每四个项目都是一个specialEvent。
问题:
应用程序用户可以点击这些事件/特殊事件中的每一个,并导航到其他屏幕。在那里,用户可以做一些事情并更改数据库内部的数据。
这将导致重建列表 View 。
根据列表 View 中的位置,构建器不会开始重建索引为0的窗口小部件。这反过来会导致evenCount和specialEventcount困惑,并且一切都变得困惑。
有人知道如何正确解决此问题吗?
我猜必须有比我的方法更好的解决方案,以便每四项构建一个特殊的小部件。
最佳答案
代替ListView.builder,使用ListView.separated,
听到是一个示例片段
ListView.separated(
itemCount: 40,
itemBuilder: (context, index) {
return ListTile(
title: Text('$index'),
);
},
separatorBuilder: (context, index) {
return index == 0
? SizedBox.shrink()
: index % 4 == 0
? Container(
height: 20,
color: Colors.red,
)
: SizedBox.shrink();
},
),
关于flutter - Flutter/Dart使用ListView.builder为每个x项构建一个不同的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62308228/