What's the difference between List take() vs. getRange() in Dart

8,805

Solution 1

The most obvious difference is that take() can only use elements at the beginning, you can combine it with skip() like list.skip(3).take(5) to get similar behavior though.
list.take() is lazy evaluated which works nice with functional style programming and might be more efficient if the elements aren't actually iterated over later.
list.take() also is tolerant when there aren't as many elements in the list as requested. take() returns as many as available, getRange() throws. take() is available on all iterables (also streams), getRange() is only available by default on list.

Solution 2

there are differences between take() and getRange()

take()

This method returns iterable starting from index 0 till the count provided from given list.

You can get the first count items of a List using take(count)

var sportsList = ['cricket', 'tennis', 'football'];

print(sportsList.take(2));     // (cricket, tennis)

getRange()

This method returns elements from specified range [start] to [end] in same order as in the given list. Note that, start element is inclusive but end element is exclusive.

You can get a group of items by specifying the range in List using getRange() method.

 var myList = [1, 2, 3, 4, 5];
 print(myList.getRange(1,4)); // (2, 3, 4)

 and also use
 var myList = [0, 'one', 'two', 'three', 'four', 'five'];
 myList.getRange(1, 3).toList();       // [one, two]
Share:
8,805
TJ Mazeika
Author by

TJ Mazeika

Updated on November 28, 2022

Comments

  • TJ Mazeika
    TJ Mazeika over 1 year

    I want the first n elements of some List. From what I can tell, I have two options: take(n) and getRange(0, n).

    1. What's the difference between them?
    2. When would I use one over the other (assuming I always want the first n elements)?