Flutter GridView Tutorial
In this Flutter GridView Tutorial we will make a little app, that displays a grid of images, which will be shown in a dialog box when clicked on it.
New Flutter App
First, we create a new Flutter App and delete everything non-essential. Also, for the sake of this tutorial we choose the theme color green. And that’s already it for this first step!
Don’t mind the _gridView() Widget here, it will be implemented in just a minute. If you want to run the empty app, checking if everything works so far, then just swap it with a Text Widget for example.
Packages for Flutter GridView Tutorial
For this tutorial, we are going to use just one small but useful package called transparent_image. It is not necessary for the GridView to work, but it makes it look a lot better. But luckily implementing packages is very easy in Flutter, just add this to the pubspec.yaml file:
Then hit Packages get at the top right corner. Done. Just don’t forget to import the package, when you need it.
Grid View Widget
First, we import the transparent_image package. Then, when we call the gridView() widget we return an actual GridView. So, for this tutorial, we just make 60 items and show them in 4 rows. Also, we add the FadeInImage widget and use a network image as our source. Let us just use Lorem Picsum here to load different images. As a placeholder, we use a transparent image from the installed package.
So far, so good. Now let us wrap this widget with a GestureDetector widget so that we can click on it and open it.
Open Image in Dialog Box
When we tap on an image we call _openImage() to open that specific image in an dialog box. We just use the alertDialog here. As content, we again use the FadeInImage widget in conjunction with the transparent_image package. Then we load this image with a slightly better resolution from Lorem Picsum (check out there website, if you don’t know how this works).
And we add a close button to the dialog box as well, which calls _dismissDialog().
Close Dialog Box
To close the dialog box, we just pop the current screen. If you don’t know how navigation works in Flutter, you can check out my tutorial on it.
And we are done. Now we should have a working app with a GridView with items that fade in. When clicked on an item, it should be opened in a dialog box.