Skip to main content

The Flutter Series: Lists and Grids (RecyclerViews in Flutter)

The Complete Flutter Series is a series of articles focused on cross-platform app development on the Flutter framework for everyone from beginners to experienced mobile developers.
In the last article about Widgets, we left out a very important aspect in Flutter: Lists. Working with a List or RecyclerView in Android meant writing a list item, an adapter and then attaching that adapter to the view in the layout file. This consumed a lot of time leading to slow development.
Flutter simplifies writing lists by eliminating most of the parts that took time in Android: No adapter, no separate list item, no attaching adapters to views.
Typical architecture of a list in native Android

Introduction to ListView in Flutter

A list in Flutter is created using the ListView widget.
There are two types of lists:
  1. User defines all items inside the list (Roughly equivalent to a ScrollView in Android)
Type I
The first type of list is just a scrollable collection of items more than a true list. Here is an example use of the ListView:
ListView(
  children: <Widget>[
    Text(
"Element 1"),
    Text(
"Element 2")
  ],
),
Because the user defines each and every item in the list individually, this behaves more like a ScrollView than a ListView or RecyclerView in Android.
This type was just included here for completeness, we are going to focus on the second type of ListView.
Type II
The second type of list is a list with repeating blocks with different data in each one. This is the equivalent of a RecyclerView, but much easier to make. To make a List like this, we use the ListView.builder() constructor.
Let’s take a look at an example ListView containing the list of Android version names:
ListView.builder(
      itemBuilder: (context, position) {
        
return Card(
          child: Text(
androidVersionNames[position]),
        );
      },
      itemCount: 
androidVersionNames.length,
)
androidVersionNames is a list of all the android version names.
This will show you a (rather not-very-pretty) list of cards with Android version names.
There are two properties inside the builder, itemBuilder and itemCount.
itemCount is pretty straightforward, it asks how many repeating items you want to display in the list.
itemBuilder is where you return the item itself that you want to display. Here we made a card with a simple text widget inside. Item builder expects a lambda function which has the parameters of context and position. Position gives you which index of the list it is.
In summary, when you make a list, you have to supply two things to it: 1) How many items in the list? 2) What does each item look like and what data does it contain?
For Android Developers: This is the complete equivalent of a RecyclerView. The itemCount builds the ViewHolder and binds index-wise data to it. This completes the role of the ViewHolder layout file and the binding function of the RecyclerView Adapter. Because there is no separate layout file, no instantiation of a LayoutManager and adapter either.
This is genuinely revolutionary compared to older methods of creating lists.

Creating Grids in Flutter

Grids are pretty similar to Lists. The widget we use is a GridView.builder instead of a ListView.builder.
Here’s an example of a GridView:
GridView.builder(
    itemBuilder: (context, position) {
      
return Card(
        child: Text(
androidVersionNames[position]),
      );
    },
    itemCount: 
androidVersionNames.length,
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),    
)
In a grid, the only fundamental difference is that it has multiple columns. So, a GridView also takes a gridDelegate which helps you set the number of columns.
(That gridDelegate name gave me strong Java nostalgia)
The crossAxisCount inside the gridDelegate is the number of columns. This can also be changed according to orientation.
Note: You can provide multiple types of items in a list or grid according to index. This is easier in Flutter because it doesn’t have different methods for creating and binding data like in native Android. The earlier “one type of item” was just mentioned for simplicity.

A more advanced example

To understand a real-world example, here’s a better looking demo ListView for an email app.
ListView.builder(
  itemBuilder: (context, position) {
    
return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.
spaceBetween,
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.
start,
              children: <Widget>[
                Padding(
                  padding:
                      
const EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 6.0),
                  child: Text(
                    
sendersList[position],
                    style: TextStyle(
                        fontSize: 22.0, fontWeight: FontWeight.
bold),
                  ),
                ),
                Padding(
                  padding:
                      
const EdgeInsets.fromLTRB(12.0, 6.0, 12.0, 12.0),
                  child: Text(
                    
subjectList[position],
                    style: TextStyle(fontSize: 18.0),
                  ),
                ),
              ],
            ),
            Padding(
              padding: 
const EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.
spaceEvenly,
                children: <Widget>[
                  Text(
                    
"5m",
                    style: TextStyle(color: Colors.
grey),
                  ),
                  Padding(
                    padding: 
const EdgeInsets.all(8.0),
                    child: Icon(
                      Icons.
star_border,
                      size: 35.0,
                      color: Colors.
grey,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        Divider(
          height: 2.0,
          color: Colors.
grey,
        )
      ],
    );
  },
  itemCount: 
sendersList.length,
),
Feel free to explore a bit more and try creating layouts of your own.
Flutter’s ListViews go above and beyond what native mobile development offer and massively save development time while still being heavily customisable.

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...