How to remove automatic SafeArea from ListView?

Viewed 18790

I just added a ListView as a child of Scaffold > Stack and it appears to have SafeArea at the top. Column does not have this problem. Is there any way for me to remove it?

Container(
  color: Colors.grey[100],
  child: ListView(
    children: <Widget>[
      Image(
        image: snapshot.data.hero,
        height: 300.0,
        fit: BoxFit.cover,
      ),
    ],
  ),
),

ListView enter image description here

Column enter image description here

4 Answers

From the ListView documentation:

By default, ListView will automatically pad the list's scrollable extremities to avoid partial obstructions indicated by MediaQuery's padding. To avoid this behavior, override with a zero padding property.

So the fix is:

ListView(
  padding: EdgeInsets.zero,
  ...
);

Found this solution as well

MediaQuery.removePadding(
  context: context,
  removeTop: true,
  child: ListView(...),
)

This is the obviously correct answer:

padding: EdgeInsets.zero

But I just wanted to add some additional info regarding this issue that helped me myself.

If you don't provide padding, it automatically uses parts of MediaQuery.of(context).padding

For example, in a vertical list view, the default padding will be this:

final EdgeInsets mediaQueryVerticalPadding =
        mediaQuery.padding.copyWith(left: 0.0, right: 0.0);

This means if you want to keep the default behavior in one part and change the other values, you should use something like this.

For example, only keeping the Top padding from the MediaQuery and editing the rest:

ListView(
    padding: MediaQuery.of(context).padding.copyWith(
        left: 0,
        right: 0,
        bottom: 50,
    ),
    ...
),

Yeah this is intentional. If you put a widget before the ListView, you should wrap the ListView with a MediaQuery.removePadding widget (with removeTop: true).

return MediaQuery.removePadding(
    context: context,
    removeTop: true,
    child: ListView(
      children: listData, //List<Widget> listData = []; added Widgets
      shrinkWrap: true,
    ),
  );

This worked best for me, even in iOS.

Related