list.filled flutter

개발을 하던 중 이차원 배열이 필요한 상황이 생겼고, Dart에서 C++, Java의 int arr[3][3]={0,} 와 같이 배열의 크기를 지정해줌과 동시에 초기화를 시킬 수 있는지 궁금했다. 

List twoDimensionalArray = List.filled[ 3,[i] => List.generate[3, [_] => false, growable: false], growable: false];


위와 같이 filled 생성자를 사용하면 손쉽게 크기를 지정해줌과 초기값을 지정해 줄 수 있었다. growable의 경우 default값은 false이며 true일 경우 확장이 가능하다. 위 코드의 경우 twoDimensionalArray = [[false, false, false], [false, false, false], [false, false, false]]3x3 크기로 생성과 동시에 false값으로 초기화된다.
다만 여기서 문제점을 찾아냈는데 twoDimensionalArray[0][0] = true; 를 했더니 예상했던 [[true, false, false], [false, false, false], [false, false, false]] 라는 값이 나오지 않고 [[true, true, true], [false, false, false], [false, false, false]] 로 값이 변환되었다.
공식문서를 찾아보니 filled로 초기화 하면 생성된 모든 요소들은 동일한 fill값을 공유한다는 사실을 알아냈다.
아래 코드를 보면 shared[0]에만 499를 추가했지만 shared[1], shared[2]에도 499라는 값이 추가된 결과를 알 수 있다. 이는 주소 값을 공유하기 때문이다.

var shared = List.filled[3, []]; shared[0].add[499]; print[shared]; // => [[499], [499], [499]]


List.generate를 사용하면 각 생성 요소들이 독립된 주소 값을 사용하여 우리가 흔히 아는 배열처럼 사용할 수 있게 된다.

var unique = List.generate[3, [_] => []]; unique[0].add[499]; print[unique]; // => [[499], [], []]

dart:core

List.filled[int length, E fill, { bool growable: false }]

Creates a list of the given length with fill at each position.

The length must be a non-negative integer.

Example:

new List.filled[3, 0, growable: true]; // [0, 0, 0]

The created list is fixed-length if growable is false [the default] and growable if growable is true. If the list is growable, changing its length will not initialize new entries with fill. After being created and filled, the list is no different from any other growable or fixed-length list created using List.

All elements of the returned list share the same fill value.

var shared = new List.filled[3, []]; shared[0].add[499]; print[shared]; // => [[499], [499], [499]]

You can use List.generate to create a list with a new object at each position.

var unique = new List.generate[3, [_] => []]; unique[0].add[499]; print[unique]; // => [[499], [], []]

Implementation

external factory List.filled[int length, E fill, {bool growable = false}];

One of the most popular data structure in OOP is List. In this tutorial, we’ll show you many methods and functions to work with a List in Dart [also in Flutter]. At the end, you’re gonna know:

  • Introduction to Dart List
  • How to create, initialize, access, modify, remove items in a List
  • Ways to iterate, find, filter, transform items of a List in Dart/Flutter
  • How to create List of objects in Dart/Flutter
  • Ways to sort a List [of objects] in Dart/Flutter
  • Initalize, iterate, flatten list of Lists

Related Posts:
– Dart/Flutter – Convert Object to JSON string
– Dart/Flutter – Convert/Parse JSON string, array into Object, List
– Dart/Flutter – Convert List to Map & Map to List

– Dart/Flutter Constructors tutorial with examples
– Dart/Flutter String Methods & Operators tutorial with examples
– Dart/Flutter Future Tutorial with Examples
– Dart/Flutter Map Tutorial with Examples

Important points about Dart List

These are some important information you should know before working with Dart List:

  • There are kinds of List: fixed-length list [list’s length cannot be changed] & growable list [size can be changed to accommodate new items or remove items]
  • Dart List is an ordered collection which maintains the insertion order of the items.
  • Dart List allows duplicates and null values.
  • While an operation on the list is being performed, modifying the list’s length [adding or removing items] will break the operation.

Create a List in Dart/Flutter

The example shows you:

  • How to create a List using List[] constructor or literal syntax.
  • How to add new items to a List.

Create fixed-length list in Dart/Flutter

List myList = List[3]; myList[0] = 'one'; myList[1] = 'two'; myList[2] = 'three'; // myList.add['four']; /* throw UnsupportedError [Unsupported operation: Cannot add to a fixed-length list] */ print[myList];

Output:

[one, two, three]

Dart also allows literal syntax and null value:

var myList = List[3]; myList[0] = 'one'; myList[1] = 2; myList[2] = null; print[myList];

Output:

[one, 2, null]

Create growable list in Dart/Flutter

We can create growable list by not specify the length of the List:

List myList = List[]; myList.add[42]; myList.add[2018]; print[myList]; print[myList.length]; myList.add[2019]; print[myList]; print[myList.length];

Output:

[42, 2018] 2 [42, 2018, 2019] 3

For growable list, Dart also allows literal syntax and null value:

var myList = List[]; // var myList = []; myList.add[42]; myList.add[null]; print[myList]; print[myList.length]; myList.add['year 2019']; print[myList]; print[myList.length];

Output:

[42, null] 2 [42, null, year 2019] 3

Dart/Flutter initialize List with values

The examples show you how to:

  • initialize list in simple way using operator [].
  • create and fill a list with specified value using filled[] constructor.
  • create a list containing all specified itemsusing from[] constructor.
  • create a ‘const’ list using unmodifiable[] constructor.
  • create and fill a list with values by a generator function using generate[] constructor.
List intList = [1, 2, 3]; print[intList]; var myList = ['one', 2]; print[myList];

Output:

[1, 2, 3] [one, 2] // by default, growable: false var fixedList = List.filled[3, 1]; print[fixedList]; // fixedList.add[42]; /* UnsupportedError [Unsupported operation: Cannot add to a fixed-length list] */ var growableList = List.filled[3, 2, growable: true]; growableList.add[42]; print[growableList];

Output:

[1, 1, 1] [2, 2, 2, 42] // by default, growable: true var fixedList = List.from[[1, 2, 3], growable: false]; print[fixedList]; // fixedList.add[42]; /* UnsupportedError [Unsupported operation: Cannot add to a fixed-length list] */ var growableList = List.from[[1, 2, 3]]; growableList.add[42]; print[growableList];

Output:

[1, 2, 3] [1, 2, 3, 42] var unmodifiableList = List.unmodifiable[[1, 2, 3]]; print[unmodifiableList]; // unmodifiableList.add[42]; /* UnsupportedError [Unsupported operation: Cannot add to an unmodifiable list] */

Output:

[1, 2, 3] // by default, growable: true var myList = List.generate[5, [index] => index * 2]; print[myList];

Output:

[0, 2, 4, 6, 8]

Combine Lists in Dart/Flutter

The examples show how to combine Lists using:

  • from[] and addAll[] method
  • expand[] method
  • operator +
  • spread operator ... or null-aware spread operator ...? [from Dart 2.3]
var list1 = [1, 2, 3]; var list2 = [4, 5]; var list3 = [6, 7, 8]; // from[] and addAll[] method var combinedList1= List.from[list1]..addAll[list2]..addAll[list3]; // expand[] method var combinedList2 = [list1, list2, list3].expand[[x] => x].toList[]; // operator + var combinedList3 = list1 + list2 + list3; // spread operator var combinedList4 = [...list1, ...list2, ...list3];

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Now, what if there is one of 3 lists above is a null list:

var list1 = [1, 2, 3]; var list2 = null; var list3 = [6, 7, 8];

If we use any methods above to combine these lists, the program will throw an Exception:
– NoSuchMethodError: The getter 'iterator' was called on null.
– or: NoSuchMethodError: The getter 'length' was called on null.

This is why null-aware spread operator ...? came to us. The operator check null list automatically with only one more ? symbol to be added:

var combinedList5 = [...?list1, ...?list2, ...?list3];

Output:

[1, 2, 3, 6, 7, 8]

Access items from List in Dart/Flutter

The examples show you how to:

  • find the size of a List using .length getter.
  • check if a List is empty or not using the getters: .isEmpty or .isNotEmpty. DON’T use .length.
  • access the item at specified index in a List using elementAt[] method or operator [].
  • modify the item at specified index in a List using operator [].
  • get a group of items by specifying the range in List using getRange[] method.
  • get the first count items of a List using take[count]
var myList = [0, 'one', 'two', 'three', 'four', 'five']; myList.isEmpty; // false myList.isNotEmpty; // true myList.length; // 6 myList.elementAt[2]; // two myList[2]; // two myList[myList.length - 1]; // five myList[3] = 3; // myList: [0, one, two, 3, four, five] myList.getRange[1, 3].toList[]; // [one, two] myList.take[3].toList[] // [0, one, two]

The examples show you how to:

var myList = [0, 'one', 'two', 'three', 'four', 'five']; // remove the item at index '3' myList.removeAt[3]; /* myList: [0, one, two, four, five] */ // remove[] returns false if the item does not exist in the List bool isRemoved = myList.remove['three']; /* isRemoved: false */ bool isRemoved4thItem = myList.remove['four']; /* isRemoved4thItem : true myList: [0, one, two, five] */ // remove all items which length > 3 myList.removeWhere[[item] => item.toString[].length > 3]; /* myList: [0, one, two] */ // remove all items in the List myList.clear[]; /* myList: [] */ var anotherList = [0, 'one', 'two', 'three', 'four', 'five']; // remove items from index 2 to 4 anotherList.removeRange[2, 5]; /* myList: [0, one, five] */

Update List item in Dart/Flutter

You can also update one or some items in a List using:

  • the item’s index
  • replaceRange[] method to remove the objects in a range, then insert others
var myList = [0, 'one', 'two', 'three', 'four', 'five']; // replace the item at index '3' myList[3] = 3; /* myList: [0, one, two, 3, four, five] */ // replace the item at index '1' myList.replaceRange[1, 2, [1]]; /* myList: [0, 1, two, 3, four, five] */ // replace the items from index 2 to 4 myList.replaceRange[2, 5, ['new 2', '3 and 4']]; /* myList: [0, 1, new 2, 3 and 4, five] */

Iterate over List in Dart/Flutter

The examples show you how to iterate over a Dart List using:

  • forEach[] and lambda expression.
  • iterator property to get Iterator that allows iterating.
  • every[] method
  • simple for-each loop
  • for loop with item index
var myList = [0, 'one', 'two', 'three', 'four', 'five']; // use forEach[] myList.forEach[[item] => print[item]]; // or myList.forEach[print]; // use iterator var listIterator = myList.iterator; while [listIterator.moveNext[]] { print[listIterator.current]; } // use every[] myList.every[[item] { print[item]; return true; }]; // simple for-each for [var item in myList] { print[item]; } // for loop with item index for [var i = 0; i < myList.length; i++] { print[myList[i]]; }

Dart/Flutter find elements in List

The examples show how to:

  • check if a List contains an element or not | contains[]
  • find the index of the first occurrence of an element | indexOf[]
  • find the index of the last occurrence of an element | lastIndexOf[]
  • find the index of the first occurrence of an element that matches a condition | indexWhere[]
  • find the index of the last occurrence of an element that matches a condition | lastIndexWhere[]
var myList = [0, 2, 4, 6, 8, 2, 8]; myList.contains[2]; // true myList.contains[5]; // false myList.indexOf[2]; // 1 myList.lastIndexOf[2]; // 5 myList.indexWhere[[item] => item > 5]; // 3 myList.lastIndexWhere[[item] => item > 5]; // 6

Filter items for a List in Dart/Flutter

The examples show how to:

  • filter all items in List that match the condition | where[]
  • get the first item in List that matches the condition | firstWhere[]
  • get the last item in List that matches the condition | lastWhere[]
var myList = [0, 2, 4, 6, 8, 2, 7]; myList.where[[item] => item > 5].toList[]; // [6, 8, 7] myList.firstWhere[[item] => item > 5]; // 6 myList.lastWhere[[item] => item > 5]; // 7

Dart/Flutter List every

We can verify if all items in a List satisfy a condition using every[] method.

var intList = [5, 8, 17, 11]; if [intList.every[[n] => n > 4]] { print['All numbers > 4']; }

Dart/Flutter List any

We can verify if at least one item in a List satisfies a condition using any[] method.

var intList = [5, 8, 17, 11]; if [intList.any[[n] => n > 10]] { print['At least one number > 10']; }

Dart/Flutter List map items into new List

We can map each item in a Dart List to new form using map[] method:

var myList = ['zero', 'one', 'two', 'three', 'four', 'five']; var uppers = myList.map[[item] => item.toUpperCase[]].toList[]; /* myList: [zero, one, two, three, four, five] uppers: [ZERO, ONE, TWO, THREE, FOUR, FIVE] */

User defined objects List in Dart/Flutter

In Dart, we can create a List of any type, from int, double, String, to complex types like a List, Map, or any user defined objects.

The example show how to create a List of user defined object:

class Customer { String name; int age; Customer[this.name, this.age]; @override String toString[] { return '{ ${this.name}, ${this.age} }'; } } main[] { List customers = []; customers.add[Customer['Jack', 23]]; customers.add[Customer['Adam', 27]]; customers.add[Customer['Katherin', 25]]; print[customers]; print[customers.length]; }

Output:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }] 3

Dart/Flutter List collection if and collection for

With the collection if and collection for, we can dynamically create lists using conditionals [if] and repetition [for].

var mobile = true; var web = false; var tringList = ['kotlin', 'dart', if [mobile] 'flutter', if [web] 'react']; // [kotlin, dart, flutter] var intList = [for [var i = 1; i < 10; i++] i]; // [1, 2, 3, 4, 5, 6, 7, 8, 9] var evenList = [ for [var i = 1; i < 10; i++] if [i % 2 == 0] i ]; // [2, 4, 6, 8]

Sort List in Dart/Flutter

The examples show you how to:

  • sort a List using sort[] method.
  • sort a List of objects using custom compare function.
  • sort a List of objects by extending Comparable abstract class.

Sort List using sort[] method

var intList = [0, 5, 2, 3, 8, 17, 11]; intList.sort[]; print[intList]; var tringList = ['vue', 'kotlin','dart', 'angular', 'flutter']; tringList.sort[]; print[tringList];

Output:

[0, 2, 3, 5, 8, 11, 17] [angular, dart, flutter, kotlin, vue]

Sort a List of objects in Dart/Flutter

- use custom compare function:

class Customer { String name; int age; Customer[this.name, this.age]; @override String toString[] { return '{ ${this.name}, ${this.age} }'; } } main[] { List customers = []; customers.add[Customer['Jack', 23]]; customers.add[Customer['Adam', 27]]; customers.add[Customer['Katherin', 25]]; customers.sort[[a, b] => a.age.compareTo[b.age]]; print['Sort by Age: ' + customers.toString[]]; customers.sort[[a, b] => a.name.compareTo[b.name]]; print['Sort by Name: ' + customers.toString[]]; }

Output:

Sort by Age: [{ Jack, 23 }, { Katherin, 25 }, { Adam, 27 }] Sort by Name: [{ Adam, 27 }, { Jack, 23 }, { Katherin, 25 }]

- The second approach is to extend Comparable abstract class and override compareTo[] method. Now we don't need to pass compare function, we just call list.sort[] instead of list.sort[compare].

class Customer extends Comparable { String name; int age; Customer[this.name, this.age]; @override String toString[] { return '{ ${this.name}, ${this.age} }'; } // sort by Name [asc], then age [desc] @override int compareTo[other] { int nameComp = this.name.compareTo[other.name]; if [nameComp == 0] { return -this.age.compareTo[other.age]; // '-' for descending } return nameComp; } } main[] { List customers = []; customers.add[Customer['Jack', 23]]; customers.add[Customer['Adam', 27]]; customers.add[Customer['Katherin', 25]]; customers.add[Customer['Jack', 32]]; customers.sort[]; print[customers]; }

Output:

[{ Adam, 27 }, { Jack, 32 }, { Jack, 23 }, { Katherin, 25 }]

Dart/Flutter List reverse

We can reverse a list using reversed property. It returns an Iterable of the objects in the list.

var tringList = ['vue', 'kotlin','dart', 'angular', 'flutter']; var reversed = List.of[tringList.reversed]; // [flutter, angular, dart, kotlin, vue]

Dart/Flutter List of Lists

Initialize List of Lists

We will:

  • initialize list of existing lists using operator [].
  • create and fill list of lists with values by a generator function using generate[] constructor.
var list1 = [1, 2]; var list2 = [3, 4]; var list3 = [5, 6]; var listOfLists = [list1, list2, list3]; // [[1, 2], [3, 4], [5, 6]] List

Video liên quan

Chủ Đề