Sorting List in Flutter - Ascending and Descending

Introduction

Sorting a list of items is a common requirement in many Flutter applications. Sorting allows users to organize data in a specific order, such as ascending or descending. In this blog post, we will explore how to implement sorting functionality in Flutter using a sample demo app. We will cover the folder structure, title, search description, and code for the app.

Ascending and Descending_Flutter_sort


Folder Structure

Here's an overview of the folder structure for our demo app:

- lib
  - models
    - item.dart
  - screens
    - sort_demo_screen.dart
  - main.dart

Code

follow_me_linkedin

Let's dive into the code for our demo app:

class Item {
  final String name;
  final int quantity;

  Item(this.name, this.quantity);
}

class SortDemoScreen extends StatefulWidget {
  @override
  _SortDemoScreenState createState() => _SortDemoScreenState();
}

class _SortDemoScreenState extends State<SortDemoScreen> {
  List<Item> items = [
    Item('Item 1', 5),
    Item('Item 3', 2),
    Item('Item 2', 10),
  ];

  bool ascending = true;

  void sortItems() {
    setState(() {
      if (ascending) {
        items.sort((a, b) => a.name.compareTo(b.name));
      } else {
        items.sort((a, b) => b.name.compareTo(a.name));
      }
      ascending = !ascending;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sort Demo'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (BuildContext context, int index) {
          final item = items[index];
          return ListTile(
            title: Text(item.name),
            subtitle: Text('Quantity: ${item.quantity}'),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: sortItems,
        child: Icon(ascending ? Icons.arrow_upward : Icons.arrow_downward),
      ),
    );
  }
}

In this code, we start by defining a data model class called `Item`. Each `Item` has a name and a quantity. The `SortDemoApp` widget sets up the MaterialApp and defines the app's theme.

The `SortDemoScreen` widget represents the main screen of our app and extends `StatefulWidget`. It maintains a list of `items` and a boolean flag `ascending` to track the current sorting order.

The `sortItems` method is responsible for sorting the list based on the item names. It toggles the sorting order between ascending and descending each time it's called.

In the `build` method, we create a `ListView.builder` to display the list of items. Each item is rendered as a `ListTile` with the item's name and quantity.

The floating action button (`FloatingActionButton`) triggers the `sortItems` method when pressed. It also displays an arrow icon pointing up or down based on the current sorting order.

Conclusion

Adding sorting functionality to a list in Flutter is essential for organizing data in a specific order. In this blog post, we explored how to implement ascending and descending sorting in Flutter using a demo app. We covered the folder structure, title, search description, and provided the code for the app. You can utilize this knowledge to enhance your Flutter applications with sorting capabilities. 

Happy coding!

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management