Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Sortable ListView In Flutter

While creating Flutter applications, now and again, we might need to give a choice to the user to sort the items in the ListView based on explicit models. This sortable ListView provides an easy-to-understand method for a survey and sorting the information in the application, making it more straightforward and quicker for them to find the data they need.

This article will explore the Sortable ListView In Flutter. We will perceive how to execute a demo program and we are going to learn about how we can create it in your Flutter applications without using any third-party packages.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code File

Conclusion



Introduction:

The below demo video tells the best way to make a Sortable ListView in a flutter. It shows how the Sortable ListView will function in your Flutter applications. It shows when the user can sort the items in the ListView by value low to high, and high to low by tapping the price label in the header of the ListView.

Demo Module :


How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

Our demo application has a ListView that shows a list of fiction items with 3 attributes: idname, and price. The header will likewise show an up or down bolt symbol demonstrating whether the items are arranged in ascending or descending request.

First, we will create a new HomePage() class. In this class, we will add the sort order. We will add a bool variable was _sortAscending is equal to true.

bool _sortAscending = true;

Now, we will add the list of products. We will add a list map of the string, dynamics, and the variable was _products.

final List<Map<String, dynamic>> _products = [
{'id': 1, 'name': 'Flutter Course', 'price': 23.99},
{'id': 2, 'name': 'ReactNative Course', 'price': 19.99},
{'id': 3, 'name': 'Python Course', 'price': 16.99},
{'id': 4, 'name': 'Swiftic Course', 'price': 35.99},
{'id': 5, 'name': 'Xamarin Course', 'price': 25.99},
];

Now, we will add the _sortProducts() method. In this method, we will add the setState() function. In this function, we sort the list of products. This function is called when the user taps the sort button.

void _sortProducts(bool ascending) {
setState(() {
_sortAscending = ascending;
_products.sort((a, b) => ascending
? a['price'].compareTo(b['price'])
: b['price'].compareTo(a['price']));
});
}

In the body, we will add a Container widget. In this widget, we will add the Row Widget. Inside the widget, we will add the header of the list that was text ‘Price Low to High’ else ‘Price High to Low’. Now, we will add the sort button for the user. We will add the InkWell widget. In this widget, we will add onTap was navigate _sortProducts(!_sortAscending), add a row widget inside a text and icons was arrow up and down.

Container(
padding: const EdgeInsets.symmetric(vertical: 29, horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
_sortAscending ? 'Price Low to High' : 'Price High to Low',
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
// the sort button
InkWell(
onTap: () => _sortProducts(!_sortAscending),
child: Row(
children: [
Text(
'Price',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.blue.shade500,
),
),
// the up/down arrow that indicates the sort order
Icon(
_sortAscending
? Icons.arrow_drop_down
: Icons.arrow_drop_up,
color: Colors.blue,
),
],
),
),
],
),
),

Now, we will add the list of products. We will add the Expanded widget. In this widget, we will add ListView.builder() method. In this method, we will add the itemCount as products. length, itemBuilder was the list item- product. We will return a Container widget. In this widget, we will add a row widget. Inside the widget, we will add three texts idname, and price.

Expanded(
child: ListView.builder(
itemCount: _products.length,
itemBuilder: (context, index) {
// the list item - product
return Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.only(bottom: 3),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${_products[index]['id']}',
style: const TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
Text(
'${_products[index]['name']}',
style: const TextStyle(
fontSize: 16.0,
),
),
Text(
'\$${_products[index]['price']}',
style: const TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
],
),
);
},
),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_sortable_listview_demo/splash_screen.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

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

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

bool _sortAscending = true;

final List<Map<String, dynamic>> _products = [
{'id': 1, 'name': 'Flutter Course', 'price': 23.99},
{'id': 2, 'name': 'ReactNative Course', 'price': 19.99},
{'id': 3, 'name': 'Python Course', 'price': 16.99},
{'id': 4, 'name': 'Swiftic Course', 'price': 35.99},
{'id': 5, 'name': 'Xamarin Course', 'price': 25.99},
];

// the function that sorts the list of products
// this function is called when the user taps the sort button
void _sortProducts(bool ascending) {
setState(() {
_sortAscending = ascending;
_products.sort((a, b) => ascending
? a['price'].compareTo(b['price'])
: b['price'].compareTo(a['price']));
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Sortable Listview Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.red.shade300,
),
body: Column(
children: [
Container(
padding: const EdgeInsets.symmetric(vertical: 29, horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
_sortAscending ? 'Price Low to High' : 'Price High to Low',
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
InkWell(
onTap: () => _sortProducts(!_sortAscending),
child: Row(
children: [
Text(
'Price',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.blue.shade500,
),
),
Icon(
_sortAscending
? Icons.arrow_drop_down
: Icons.arrow_drop_up,
color: Colors.blue,
),
],
),
),
],
),
),
Expanded(
child: ListView.builder(
itemCount: _products.length,
itemBuilder: (context, index) {
// the list item - product
return Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.only(bottom: 3),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${_products[index]['id']}',
style: const TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
Text(
'${_products[index]['name']}',
style: const TextStyle(
fontSize: 16.0,
),
),
Text(
'\$${_products[index]['price']}',
style: const TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
],
),
);
},
),
),
],
),
);
}
}

Conclusion:

In the article, I have explained the Sortable ListView basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Sortable ListView On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Sortable ListView in your Flutter projectsWe will show you what the Introduction is. Make a demo program for a working Length Converter in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.