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

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

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...