How to return a widget if it is the last index of a list?

Viewed 3732

i want to retun a widget if it is the last item in the method but i get an error ... Tried calling: call()

 itemList.last()
     ? CircleAvatar(
       backgroundColor: mainColor,
       radius: 15,
       child: Icon(Icons.done),
        )
      : Container()

2 Answers

assuming your are using a ListView.builder()

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    List<String> item = [
      'jan',
      'feb',
      'mar',
      'apr',
      'may',
      'jun',
      'jul',
      'aug',
      'sep',
      'oct',
      'nov',
      'dec'
    ];
    return Scaffold(
      body: ListView.builder(
        itemCount: item.length,
        itemBuilder: (context, index) {
          if (index == item.length - 1) {
            return ListTile(
              leading: Text('Last index reached'),
            );
          }
          return ListTile(
            leading: Text(item[index]),
          );
        },
      ),
    );
  }
}

Your question is so vague. I will assume that you are looping on a list and want to show a specific widget when it comes to the last element.

so all you have to do is just check if the index you are at is equal to the length of the list -1

i.e

for (int i=0;i<myList.length;i++) {
    if (i == myList.length -1) {
         return CircleAvatar(
             backgroundColor: mainColor,
             radius: 15,
             child: Icon(Icons.done),
         );
    } else {
          return Container();
    }
}
Related