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:
- List Items can be separated into groups.
- An individual header can be given to each group.
- 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:
Similar Reads
Flutter - Horizontal List
In Flutter there can be Two types of lists, namely, horizontal list and vertical list. Both these lists are created using the ListView constructor and assigning the scrollDirection parameter. By default, the scroll direction parameter is vertical for a vertical list but it can be overridden by passi
3 min read
Flutter - GridPaper Widget
A grid paper is a paper that has a grid on it with divisions and subdivisions, for example, graph paper. We may use grid paper in creating the graphs in our flutter application. A sample image is given below to get an idea about what we are going to do in this article. Â How to use it?Dart GridPaper(
3 min read
Flutter - GridView
Flutter's GridView is a widget similar to a 2-D array found in many programming languages. As its name indicates, the GridView widget is used to display content in a grid format. This allows us to showcase images, text, icons, and more within the GridView. There are several ways to implement GridVie
6 min read
Flutter - Dynamic Image List
Dynamic Image List is the list of Images when we add images Dynamically, In this article, we will see how to add images dynamically to the List of Images. It is something like that we are adding some items to the list. There is no need to add dependency to our project. A sample video is given below
5 min read
Flutter - Using Tuples
A tuple is a collection of items that could be dissimilar. It is the list-like data type. Since it is not a built-in data type in Flutter we need a tuple package to include it in the project. Let's discuss tuple in the Flutter in this article. Add in the Dependency: In Flutter, a tuple needs to be a
2 min read
SQLite in Flutter
SQLite is a very popular choice of local storage database. It is an SQL lightweight and serverless database engine that is highly efficient and user-friendly. Flutter, Google's UI toolkit for building natively compiled applications, doesn't come with built-in support for local data storage but provi
5 min read
Flutter - Inherited Widget
If you are a flutter developer then you know how easy is to create Flutter UI. But when you have lots of widgets in your app and you want to pass data from one widget to another widget, this will be a pain for many developers,s especially for the newbie, this will be really hard for them to pass the
6 min read
SliverList in Flutter
In Flutter, with slivers, we can create different scrolling effects. Slivers give an amazing view of the lists when they scroll up or down. The slivers allow us to impact the Lists, Grids scrolling experience. In this article, we will be looking at Slivers features offered by the sliver_tools packag
4 min read
Flutter - Stepper Widget
In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. Stepper is generally used in filling forms online. For example, remember filling an online form for applying to any university or passport or driving license. We filled
8 min read
Flutter - Padding Widget
Padding widget in flutter does exactly what its name says, it adds padding or empty space around a widget or a bunch of widgets. We can apply padding around any widget by placing it as the child of the Padding widget. The size of the child widget inside padding is constrained by how much space is re
3 min read