1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Dart List型の使い方

Last updated at Posted at 2024-03-30

Dartのコレクション型 Listの使用方法

Dart言語におけるコレクション型には、List、Set、Queue、Mapの4種類があります。
今回はListの使用方法について説明します。

目次

List型について

List型は順序付けられた要素のコレクションです。重複する要素を持つことができます。

使用方法

Listの宣言方法は以下になります。

List<String> fruitsNames = ['apple', 'banana', 'grape'];

fruitsNames.add('orange');

print(fruitsNames); // 出力結果:[apple, banana, grape, orange]

List<データの型> 変数名 = [データ内容1, データ内容2, データ内容3]; の形式でリストを初期化できます。

主なメソッド

add(element): 特定の値をリストの最後に追加します。

List<String> fruits = ['apple', 'grape'];
fruits.add('banana'); // 'banana' をリストの最後に追加します。
print(fruits); // 出力: ['apple', 'grape', 'banana']

remove(fruits):リストから特定の値を削除します

リストから特定の値を削除します。
List<String> fruits = ['apple', 'banana', 'grape'];
bool result = fruits.remove('banana');
print(fruits); // 出力: ['apple', 'grape']
print(result); // 出力: true

removeAt(index): 指定したインデックスにある要素をリストから削除します。

void main() {
  List<String> fruits = ['apple', 'banana', 'grape'];
String removedFruit = fruits.removeAt(1); // 'banana'が削除されます。
print(fruits); // 出力: ['apple', 'grape']
print(removedFruit); // 出力: banana
}

indexOf(element): 特定の値を検索し、そのインデックスを返します。

List<String> fruits = ['apple', 'banana', 'grape'];
int index = fruits.indexOf('banana'); // 'banana'のインデックスを検索します。
print(index); // 出力: 1

insert(index, element): 指定したインデックスに要素を挿入します。

List<String> fruits = ['apple', 'grape'];
fruits.insert(1, 'banana'); // インデックス1の位置に'banana'を挿入します。
print(fruits); // 出力: ['apple', 'banana', 'grape']
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?