Shahzad Akram
Shahzad Akram

Reputation: 5254

Dart custom sorting of a list

I want to build a suggestion builder where I want to display search suggestions on changing the text in TextField. I want to search on the basis of contains method but I want to sort that particular list on the basis of startsWith, If I only use startsWith it neglects all other contains, How can I apply both simultaneously? I have a List,

List<String> list = ["apple", "orange", "aaaaorange", "bbbborange","cccccorange"]

Now If I put only ora in search it's returning me in the following order,

aaaaorange
bbbborange
cccccorange
orange

What I want.

orange
aaaaorange
bbbborange
cccccorange

Code:

            return list
                .where((item) {
              return item.toLowerCase().contains(query.toLowerCase());
            }).toList(growable: false)
                  ..sort((a, b) {
                    return a.toLowerCase().compareTo(b.toLowerCase());
                  });

Upvotes: 0

Views: 662

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

It may be easiest to think of the two queries separately, and then combine the results:

  var list = <String>[
    'apple',
    'orange',
    'aaaaorange',
    'bbbborange',
    'cccccorange',
  ];
  var pattern = 'ora';

  var starts = list.where((s) => s.startsWith(pattern)).toList();
  var contains = list
      .where((s) => s.contains(pattern) && !s.startsWith(pattern))
      .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

  var combined = [...starts, ...contains];
  print(combined);

Upvotes: 1

Related Questions