listflutterdartlastindexof

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


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


Solution

  • 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]),
              );
            },
          ),
        );
      }
    }