Home > Back-end >  Flutter: Add padding to only certain elements in my ListView
Flutter: Add padding to only certain elements in my ListView

Time:01-20

I'm trying to create a ListView and would only want the first item to be padded. Here is the code:

Expanded(
     child: ListView.builder(
       padding: EdgeInsets.all(16),
       itemCount: card.length,
       itemBuilder: (context, index) {
       if (index == 0) {
           return MyCard.buildRecordCard(
            card[index], context);
       } else {
          return MyCard.buildRecordsCards(
            card[index], context, index);
      }
    },
  ),
);

The output looks as follows: current output

but I want cards 2...n (i.e. index != 0) not to be padded and to stretch out to the end of the screen. Something like this:

if (index == 0) {
    padding: EdgeInsets.all(16),
    return MyCard.buildRecordCard(
      card[index], context);
} else {
    padding: 0,
    return MyCard.buildRecordsCards(
       card[index], context, index);
}

but that obviously doesn't work.

CodePudding user response:

You just needed to wrap the widget with Padding. simply you can use ternary like

itemBuilder: (context, index) {
  return Padding(
      padding: index == 0 ? EdgeInsets.all(16) : EdgeInsets.zero,
      child: MyCard.buildRecordCard(card[index], context));
},

CodePudding user response:

Solved. I just added the padding to the item I was building by wrapping it in a container as follows:

Container(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
        child: ...ListTile...
  • Related