Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Sort List on Alphabetical Order in Dart/Flutter

In this example, we are going to show you how to sort an Array List in Alphabetical order in both ascending and descending forms in Dart/Flutter. See the example below for more Details.

Read This Also: How to Sort List by Date in Dart/Flutter

Sort List on Alphabetical Order [Ascending]:

List<String> countries = [
    "Nepal", 
    "India", 
    "Pakistan",
    "Bangladesh",
    "USA",
    "Canada",
    "China",
    "Russia",
];

countries.sort((a, b){ //sorting in ascending order
    return a.compareTo(b);
});
print(countries);
//output: [Bangladesh, Canada, China, India, Nepal, Pakistan, Russia, USA]

Sort List on Alphabetical Order [Descending]:

List<String> countries = [
    "Nepal", 
    "India", 
    "Pakistan",
    "Bangladesh",
    "USA",
    "Canada",
    "China",
    "Russia",
];

countries.sort((a, b){ //sorting in descending order
    return b.compareTo(a);
});
print(countries);
//output: [USA, Russia, Pakistan, Nepal, India, China, Canada, Bangladesh]

Swap the position of 'a' and 'b' while comparing to sort in descending order.

Full Flutter/Dart Code Example:

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

    List<String> countries = [
        "Nepal", 
        "India", 
        "Pakistan",
        "Bangladesh",
        "USA",
        "Canada",
        "China",
        "Russia",
    ];

    countries.sort((a, b){ //sorting in ascending order
        return a.compareTo(b);
    });

    return Scaffold(
         appBar: AppBar(
            title: Text("Sorting List Alphabetically"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:countries.map((cone){
                  return Container(
                    child: Card(
                       child:Container( 
                         width: double.infinity,
                         padding: EdgeInsets.all(15),
                         child: Text(cone, style: TextStyle(fontSize: 18))),
                       ),
                  );
               }).toList(),
             ),
          )
      );
  }
}

Output Screenshot:

In this way, you can sort Array List in alphabetical order in Dart/Flutter.

No any Comments on this Article


Please Wait...