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

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 = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...