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

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]

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.

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(),
             ),
          )
      );
  }
}

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

No any Comments on this Article


Please Wait...