2

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()

ialyzaafan
  • 378
  • 6
  • 21

2 Answers2

6

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]),
          );
        },
      ),
    );
  }
}
Mr Random
  • 1,992
  • 7
  • 20
  • itemList.last will return the last element, which is probably not a boolean type so this is not the correct way to do this. https://api.dart.dev/stable/2.10.4/dart-core/List/last.html – omar hatem Dec 03 '20 at 21:24
4

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();
    }
}
omar hatem
  • 1,799
  • 1
  • 10
  • 23