How I can show last 5 elements in widget with listview.builder? Thanks!
if (snapshot.hasData) {
return ListView.builder(
controller: controller,
// shrinkWrap: true,
// reverse: true,
itemCount: snapshot.data!.length ,
itemBuilder: (BuildContext context, int index) {
// controller.jumpTo(controller.position.maxScrollExtent);
if (snapshot.data![index].operatorName == 'barz1' ||
snapshot.data![index].operatorName == 'barz2') {
return Container(
CodePudding user response:
You can set reverse
property true in Listview.builder
and set itemcount
to 5 to get last 5 elements in widget with ListView.Builder
.
ListView.builder(
reverse: true,
itemCount: 5,
itemBuilder: (ctx, index) {
return Container();
},
);
CodePudding user response:
you can use this method
if (snapshot.hasData) {
final originalList=snapshot.data;
final newList=originalList.sublist(originalList.length-5, originalList.length);
return ListView.builder(
controller: controller,
// shrinkWrap: true,
// reverse: true,
itemCount: newList.length ,
itemBuilder: (BuildContext context, int index) {
// controller.jumpTo(controller.position.maxScrollExtent);
if (newList[index].operatorName == 'barz1' ||
newList[index].operatorName == 'barz2') {
return Container(
CodePudding user response:
Try this:
if (snapshot.hasData) {
return ListView.builder(
controller: controller,
itemCount: snapshot.data!.length ,
itemBuilder: (BuildContext context, int index) {
if(index > snapshot.data!.length - 5){ /// <--- add this condition
if (snapshot.data![index].operatorName == 'barz1' ||
snapshot.data![index].operatorName == 'barz2') {
return Container(...);
}
}
}
);
}
CodePudding user response:
You can create sublist from original data.
class Fas4 extends StatelessWidget {
const Fas4({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<int>>(
future: Future.value(List.generate(333, (index) => index)),
builder: (context, snapshot) {
//handle other state like error...
if (snapshot.hasData) {
final data = snapshot.data ?? [];
List<int> subList =
data.length <= 5 ? data : data.sublist(data.length - 6);
return ListView.builder(
itemCount: subList.length,
itemBuilder: (context, index) => Text("${subList[index]}"),
);
}
return Text("Loading");
},
),
);
}
}