I have a list of 10 items that I am displaying with a listview.builder. I want to display an item in between the listview after suppose 3 items in the list, how can I do that?
CodePudding user response:
Yes. there is a builder called Listview.separated()
ListView.separated(
itemCount: 10,
itemBuilder: (context, index) => const ListTile(),
separatorBuilder: (context, index) {
if (index == 3) {
// add widget after three item
return Container();
}
return const SizedBox.shrink();
},
),
CodePudding user response:
Building on Sanjay's answer, this should add it in the middle of the list without affecting the list
var list = [val1, val2, val3, ..];
ListView.separated(
itemCount: list.length,
itemBuilder: (context, index) => const ListTile(),
separatorBuilder: (context, index) {
// For even list length case
if (list.length % 2 == 0 && index == list.length/2) {
return YourSeparator();
}
// For odd list length case (if you want it before the middle item then
// change to floor())
else if (list.length % 2 == 1 && index == (list.length/2).ceil() ) {
return YourSeparator();
} else {
return SizedBox();
}
},
),