In this article, youβll learn how to create a scrollable horizontal list, in our case filled with avatars.
However, feel free to put whatever you want on this list. The result for today will look like this:
For this article, weβll be starting from our basic Flutter application, which you can download on GitHub as well.
Render avatars in Flutter
First, letβs start by rendering avatars in Flutter, as this will be the basis of our application.
Usually, we would be able to use a CircleAvatar
widget in Flutter. I want to include a border around the widget for my version, so Iβm using a container to wrap everything.
return Center(
child: Container(
width: 120.0,
height: 120.0,
padding: EdgeInsets.all(2),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: CircleAvatar(
backgroundImage: NetworkImage('{YOUR_IMAGE}'),
),
),
);
And with this, we get a circle image with a black border around it.
The last thing Iβll do here is extract this to be its very own widget so we can easily re-use it. I use Visual Studio to extract this into its widget resulting in the following code:
class SampleAvatar extends StatelessWidget {
const SampleAvatar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: 120.0,
height: 120.0,
padding: EdgeInsets.all(2),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: CircleAvatar(
backgroundImage: NetworkImage(
'https://media-exp1.licdn.com/dms/image/C4D03AQFgZBilNtPUMA/profile-displayphoto-shrink_800_800/0/1604728137407?e=1632960000&v=beta&t=QKa1Nq3WKWQGEGaiKdZ1ovp1h6uAbwPZfihdqY2_pNU'),
),
);
}
}
Making it easy for us to use like so:
SampleAvatar()
Creating a horizontally scrollable list view in Flutter
Now that we have our sample avatar widget letβs go ahead and see how we can make a horizontally scrollable list including them.
return Container(
margin: EdgeInsets.all(10.0),
height: 140.0,
child: ListView.separated(
itemCount: 10,
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
width: 10,
);
},
itemBuilder: (_, i) => SampleAvatar(),
scrollDirection: Axis.horizontal,
),
);
This code creates a container to add some margin and height to our scrollable list.
Inside, we render the ListView
. I chose to use the separated one since we want some space between each item.
Then inside, we render each of our sample avatars.
And the most important part, we define the scrollDirection
as Axis.horizontal
making it scroll horizontally.
And thatβs all we need to create a horizontally scrollable list in Flutter.
If you are looking for the complete code for either our avatar widget or the full list view, you can find it on GitHub.
Thank you for reading, and letβs connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter