skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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...
    

  2. 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));
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search