Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a string list alphabetically in Dart language? [duplicate]

I have 4 companies and each company has more than 10 branches. If a user chooses a company, I need to show the selected company branch using showDialog. Till here everything work as expected. My problem is that I cannot sort List<String> alphabetically.

Any idea how to sort string list (List) alphabetically in Dart?

List<String> _myBranchListName;
like image 382
Nick Avatar asked Jan 07 '19 10:01

Nick


2 Answers

  • Flutter is an application development SDK

  • Dart is a general-purpose programming language

  • Flutter application is written in Dart

  • so:

    How to sort A to Z in Flutter List< String > ?

  • Will be

    How to sort A to Z in Dart List< String > ?

  • A to Z : is called alphabetically so :

    How to sort alphabetically in Dart List< String > ?

  • List< String > : is a list of type string so

    How to sort alphabetically in Dart String List?

  • more

    How to sort a string list alphabetically in Dart language?

Code:

main() {
  List<String> _myBranchListName= ['k branch', 'a branch', 'f branch'];

  _myBranchListName.sort();
  print(_myBranchListName);

  //[a branch, f branch, k branch]
}

update

I have a custom list with menas list contain class produt and product contain varable title and now i need to short my list based on title how to do it''' comment

  • base on sort method - List class - dart:core library - Dart API

sort method:

Sorts this list according to the order specified by the compare function.

The default List implementations use Comparable.compare if compare is omitted.

A Comparator may compare objects as equal (return zero),

even if they are distinct objects. The sort function is

not guaranteed to be stable, so distinct objects that

compare as equal may occur in any order in the result

  • your code (😊Waring: i did not test this code i need your feedback):

produts.sort((a, b) => a.title.compareTo(b.title));

like image 124
Mohamed Elrashid Avatar answered Nov 17 '22 12:11

Mohamed Elrashid


List Contains method called sort, that function will sort the list in alphabetical order (from a to z).

I created function for you to make the process more clear:

List<String> sort(List<String> _myBranchListName){    // This function take List of strings and return it organized alphabetically
 // List<String> _myBranchListName = ["B branch", "C branch" , "A branch"]; // example of input
  print(_myBranchListName);   // will show the result in the run log
  _myBranchListName.sort();
  print(_myBranchListName);   // will show the result in the run log
  return _myBranchListName;
}

Technically you only need _myBranchListName.sort() to sort the array.

like image 3
Guy Luz Avatar answered Nov 17 '22 10:11

Guy Luz