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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...