Open In App

Flutter - Grouped List

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The grouped_list package in Flutter as the name suggests is used to create list items in different groups. This package also provides 3 specific functions that are listed below:

  1. List Items can be separated into groups.
  2. An individual header can be given to each group.
  3. Most fields from the ListView.builder are available in this library.

Constructor of GroupedListView

 GroupedListView<dynamic, String> GroupedListView({
Key? key,
required List<dynamic> elements,
required String Function(dynamic) groupBy,
int Function(String, String)? groupComparator,
Widget Function(String)? groupSeparatorBuilder,
Widget Function(dynamic)? groupHeaderBuilder,
Widget Function(dynamic)? groupStickyHeaderBuilder,
Widget? emptyPlaceholder,
Widget Function(BuildContext, dynamic)? itemBuilder,
Widget Function(BuildContext, dynamic, bool, bool)? groupItemBuilder,
Widget Function(BuildContext, dynamic, int)? indexedItemBuilder,
Widget Function(BuildContext, dynamic, dynamic, dynamic)? interdependentItemBuilder,
int Function(dynamic, dynamic)? itemComparator,
GroupedListOrder order = GroupedListOrder.ASC,
bool sort = true,
bool useStickyGroupSeparators = false,
Widget separator = const SizedBox.shrink(),
bool floatingHeader = false,
Color stickyHeaderBackgroundColor = const Color(0xffF7F7F7),
Axis scrollDirection = Axis.vertical,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
bool reverse = false,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
Clip clipBehavior = Clip.hardEdge,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
String? restorationId,
int? semanticChildCount,
double? itemExtent,
Widget? footer,
})

Key Parameters:

The below list holds all the parameters of the GroupedListView with their explanation:

Property

Description

element

It is a required field, which comprises the content that is to be displayed in the list

groupBy

It is also a required field, which maps the content and the groups using this function

itemBuilder / indexedItemBuilder

It is called to build children for the list with 0 <= element < elements.length

separator

It separates the content of one group from another

order

It sets the order (ascending or descending) in which the grouped list is displayed

Steps to Implement Grouped List

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add grouped_list as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
  flutter:
    sdk: flutter
  grouped_list: ^6.0.0


Now run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add grouped_list


Step 3: Import dependencies

To use libraries, import all of them in the respective .dart file,

import 'package:grouped_list/grouped_list.dart';


Step 4: Working With main.dart

Add the boilerplate code below in main.dart to create a basic structure with an AppBar and body using a Scaffold.

Dart
import 'package:flutter/material.dart';
import 'package:grouped_list/grouped_list.dart';

// Entry point of the application
void main() => runApp(MyApp());

// Main application widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Disable debug banner
      debugShowCheckedModeBanner: false,
      home: GroupListClass(),
    );
  }
}

class GroupListClass extends StatefulWidget {
  const GroupListClass({super.key});

  @override
  State<GroupListClass> createState() => _GroupListClassState();
}

class _GroupListClassState extends State<GroupListClass> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksForGeeks'), 
        backgroundColor: Colors.green, 
        foregroundColor: Colors.white, 
      ),
      body: // Code Here
  }
}

Step 5: Initialize variables

Initialize the required variables in the _GroupListClassState class.

Dart
// Sample data to be displayed in the grouped list
final List _elements = [
    {'name': 'Virat Kohli', 'group': 'RCB'},
    {'name': 'Rohit Sharma', 'group': 'MI'},
    {'name': 'AB de Villiers', 'group': 'RCB'},
    {'name': 'Jasprit Bumrah', 'group': 'MI'},
    {'name': 'KL Rahul', 'group': 'KXIP'},
    {'name': 'Md. Shammi', 'group': 'KXIP'},
];


Step 6: Working with GroupedListView

Now, use the below code in the body:

Dart
GroupedListView<dynamic, String>(
    // List of elements to display
    elements: _elements,
    // Group elements by 'group' key
    groupBy: (element) => element['group'],
    // Sort groups in descending order
    groupComparator: (value1, value2) => value2.compareTo(value1),
    // Sort items within a group alphabetically
    itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']),
    // Order groups in descending order
    order: GroupedListOrder.DESC,
    // Enable sticky group headers
    useStickyGroupSeparators: true,
    groupSeparatorBuilder: (String value) => Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(
        value,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
      ),
    ),
    itemBuilder: (c, element) {
      return Card(
        elevation: 8.0,
        margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
        child: Container(
          child: ListTile(
            contentPadding:EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
            leading: ImageIcon(
              NetworkImage(
                  'http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png'
                  ), // Leading icon
            ),
            // Display player's name
            title: Text(element['name']),
          ),
        ),
      );
   },
),


Complete Source Code:

main.dart:

Dart
import 'package:flutter/material.dart';
import 'package:grouped_list/grouped_list.dart';

// Entry point of the application
void main() => runApp(MyApp());

// Main application widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Disable debug banner
        debugShowCheckedModeBanner: false,
        home: GroupListClass());
  }
}

class GroupListClass extends StatefulWidget {
  const GroupListClass({super.key});

  @override
  State<GroupListClass> createState() => _GroupListClassState();
}

class _GroupListClassState extends State<GroupListClass> {
    // Sample data to be displayed in the grouped list
    final List _elements = [
        {'name': 'Virat Kohli', 'group': 'RCB'},
        {'name': 'Rohit Sharma', 'group': 'MI'},
        {'name': 'AB de Villiers', 'group': 'RCB'},
        {'name': 'Jasprit Bumrah', 'group': 'MI'},
        {'name': 'KL Rahul', 'group': 'KXIP'},
        {'name': 'Md. Shammi', 'group': 'KXIP'},
    ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksForGeeks'), 
        backgroundColor: Colors.green, 
        foregroundColor: Colors.white, 
      ),
      body: GroupedListView<dynamic, String>(
        // List of elements to display
        elements: _elements,
        // Group elements by 'group' key
        groupBy: (element) => element['group'],
        // Sort groups in descending order
        groupComparator: (value1, value2) => value2.compareTo(value1),
        // Sort items within a group alphabetically
        itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']),
        // Order groups in descending order
        order: GroupedListOrder.DESC,
        // Enable sticky group headers
        useStickyGroupSeparators: true,
        groupSeparatorBuilder: (String value) => Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            value,
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold
            ),
          ),
        ),
        itemBuilder: (c, element) {
          return Card(
            elevation: 8.0,
            margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
            child: Container(
              child: ListTile(
                contentPadding:EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                leading: ImageIcon(
                  NetworkImage(
                      'http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png'
                      ), // Leading icon
                ),
                // Display player's name
                title: Text(element['name']),
              ),
            ),
          );
        },
      ),
    );
  }
}

 
 Output:

Flutter_Grouped_List


 


Next Article

Similar Reads