Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thanks for the question! You can sort a list of Strings like this:</p> <pre class="lang-dart prettyprint-override"><code>main() { var fruits = ['bananas', 'apples', 'oranges']; fruits.sort(); print(fruits); } </code></pre> <p>The above code prints:</p> <pre class="lang-dart prettyprint-override"><code>apples, bananas, oranges </code></pre> <p>Notice that <code>sort()</code> does not return a value. It sorts the list without creating a new list. If you want to sort and print in the same line, you can use <em>method cascades</em>:</p> <pre class="lang-dart prettyprint-override"><code>print(fruits..sort()); </code></pre> <p>For more control, you can define your own comparison logic. Here is an example of sorting the fruits based on price.</p> <pre class="lang-dart prettyprint-override"><code>main() { var fruits = ['bananas', 'apples', 'oranges']; fruits.sort((a, b) =&gt; getPrice(a).compareTo(getPrice(b))); print(fruits); } </code></pre> <p>Let's see what's going on here.</p> <p>A List has a <a href="https://api.dartlang.org/apidocs/channels/be/dartdoc-viewer/dart:core.List#id_sort" rel="noreferrer">sort</a> method, which has one <em>optional</em> parameter: a <a href="http://api.dartlang.org/docs/continuous/dart_core/Comparator.html" rel="noreferrer">Comparator</a>. A Comparator is a <code>typedef</code> or function alias. In this case, it's an alias for a function that looks like:</p> <pre class="lang-dart prettyprint-override"><code>int Comparator(T a, T b) </code></pre> <p>From the docs:</p> <blockquote> <p>A Comparator function represents such a total ordering by returning a negative integer if a is smaller than b, zero if a is equal to b, and a positive integer if a is greater than b.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload