Martin Schultz
Martin Schultz

Reputation: 2861

Flutter ListView - center items if not expanding beyond screen

I have a horizontal ListView and depending on the app state, there might be 1-2 items in the list or many.

Now, I want to have the items centered as long as there are only a few available and scrolling is not needed. So far my items always stick to the left side as you can see in the ListView with the lime background color. That one I wanted centered, even if 2 or 3 items are visible, but with more, it shall scroll and then start at the left side with listing the items.

    return Container(
        color: Colors.lime,
        child: ListView(
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            children: listItems));

the items itself are this:

  Widget getPersonCircleWidget(BuildContext context, Person p) {
    return Container(
      color: Colors.transparent, //yellow,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: CircularProfileAvatar('',
            child: Image(
                fit: BoxFit.cover,
                image:
                    UserPhotoManager.singleton.getUserProfilePhoto(p.userId)),
            borderColor: colorCirclePhotoBorder,
            borderWidth: 2,
            elevation: 10,
            radius: 40,
            onTap: () {
               ....
        }),
      ),
    );
  }

Any idea how to solve this?

enter image description here

Upvotes: 1

Views: 1077

Answers (1)

Blasanka
Blasanka

Reputation: 22437

Just wrap your ListView with Center widget.

Center(
  child: ListView(
    shrinkWrap: true,
    scrollDirection: Axis.horizontal,
    children: listItems.map<Widget>((a) => CircleAvatar(
      child: Text(a))).toList(),
    ),
),

When ListView exceed available room on the screen it will automatically left aligned.

Try it on dartpad.

Upvotes: 3

Related Questions