List的語法

 avatar
Michael
dart
a year ago
7.3 kB
3
Indexable
main() {
  // List初始化 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

  // 空list
  // var anEmptyList = <int>[];
  var anEmptyList = List<int>.empty(growable: true); // growable:可否擴充
  anEmptyList.addAll([1,2,3]);
  print(anEmptyList);

  // filled(length, element filled)
  var lii = List<int>.filled(5,0,growable: true);
  lii.add(123);
  print('List.filled: $lii');

  // generate(length, for each index匿名函數
  var squaredList = List<int>.generate(4, (index) => index * index, growable: false);
  print('squaredList: $squaredList');
  // squaredList.add(123);

  // List.from(iterable,{growable=true})  growable:可否擴充
  Set<String> originalSet = {'apple', 'banana', 'orange'};
  List<String> newListFromSet = List.from(originalSet, growable: true);
  newListFromSet.add('waterlemon'); // growable: false==>Cannot add to a fixed-length list
  print('Set to List: $newListFromSet');

  // 常量 List
  const lis345 = [1, 2, 3];
  // lis345[0]=23;
  // lis345=[4,5,6];

  List<int> lis456 = const [1, 2, 3];
  // lis456[0]=23;
  lis456 = [4, 5, 6];

  // List.unmodifiable(iterable elements) 效果跟const list一樣, 每個元素都不可更改
  List<int> intList=[1,2,3];
  List<int> unmodifiableList=List.unmodifiable(intList);
  print('unmodifiableList= $unmodifiableList');
  // unmodifiableList.add(44);
  // unmodifiableList.setAll(1,[44,55]);
  // unmodifiableList[0]=23;
  // unmodifiableList.length=4;
  unmodifiableList=[4,5,6];
  print('unmodifiableList= $unmodifiableList');

  /*
  final宣告的 變數A 儲存的是一塊List B 資料的address C
  List B 的元素變動時, 該address C不會被改變,
  所以final會允許,
  但 變數A 重新賦值另一個新的 List D
  繫結用的address D是新的
  此時final不允許
  */

  final List a=[1,2,3];
  a[0]=12;
  print('list changed: $a');
  a.setAll(0, [4,5]);
  print('list changed: $a');
  // a=[1,2,3]; // final a只能賦值一次, 不能儲存新的list address

  // nullable type, List.length 可以變長變短
  List<String?> nullableList = List.from(newListFromSet, growable: true);
  nullableList.length += 1;
  print('length+=1: $nullableList'); // [apple, banana, orange, waterlemon, null]
  nullableList[nullableList.length - 1] = 'mongo';
  print('length+=1: $nullableList'); // [apple, banana, orange, waterlemon, mongo]
  nullableList.length=3; // 截短 [apple, banana, orange]
  print('length=3: $nullableList');

  // List元素可以不同類型 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  var lis1 = [10, true, 12.22, 'adf'];
  print('List元素可以不同類型\n$lis1');

  // 判斷類型
  print('類型判定: ${lis1 is List}');

  // 指定元素類型
  List<num> lis2 = [45, 12.3];
  print('指定類型法1\n$lis2');

  var lis3 = <String>['a', 'n'];
  print('指定類型法2\n$lis3');

  // 空List
  var lis4 = <num>[];
  print('空List長度\n${lis4.length}');

  print('List 常用屬性-----------------------------');
  print('length: ${lis3.length}');
  print('reversed: ${lis3.reversed.toList()}');
  print('isEmpty: ${lis3.isEmpty}');
  print('isNotEmpty: ${lis3.isNotEmpty}');

  // 常用方法
  lis4.add(1);
  lis4.add(2);
  lis4.addAll([3, 4, 5]);
  print('List.add addAll\n$lis4');
  print('index of num 5: ${lis4.indexOf(5)}');

  print('before remove:$lis4');
  print('List remove from end: ${lis4.removeLast()}');
  print('List remove by index 1: ${lis4.removeAt(1)}');
  print('after remove:$lis4');

  lis4.insert(1, 456);
  print('insert(index,value): $lis4');
  lis4.insertAll(0, [77, 88]);
  print('insertAll(index,iteral): $lis4');

  print('toList(): ${{1, 2, 3}.toList()}');

  var lis0 = ['List', 'joined', 'by', 'space'];
  print(lis0.join(' '));

  var lisss = '  aaa   ,   bbb  ,   ccc   '.split(',');
  assert(lisss is List);
  lisss = [for (var i in lisss) i.trim()];
  print('String is splitted and trimed to a List: $lisss');

  print('List.filled(int length,<T>value)');
  List<int> numbers = List.filled(5, 999); // 創建一個長度為5的List,初始值為0
  print(numbers);
  print('List.fillRange(start,end,value)');
  numbers.fillRange(1, 4, 1); // 在索引1到4的範圍內填充值1
  print(numbers);

  print('轉換List中的元素, Iterable<T> map<T>(T Function(E element) f)');
  List<int> ascii = [65, 66, 67];
  List<String> chr = ascii.map((int i) => String.fromCharCode(i)).toList();
  print(chr);

  /*
    where方法用於過濾Iterable(例如List、Set)中的元素,
    並返回滿足特定條件的元素。它接受一個函式作為參數,
    該函式對每個元素進行評估,並返回一個布林值,指示該元素
    是否滿足條件。

    Iterable<T> where(bool Function(T element) test)
    這裡,T是Iterable中的元素類型,test是一個函式,它接受一個元素
    作為參數並返回一個布林值。
   */
  List<int> numbers1 = [1, 2, 3, 4, 5];
  Iterable<int> evenNumbers = numbers1.where((int number) => number % 2 == 0);
  print('where: ${evenNumbers.toList()}'); // 輸出:(2, 4)

  /*
    any方法用於檢查Iterable(例如List、Set)中
    是否存在至少一個元素滿足指定條件
    bool any(bool Function(T element) test)
  */
  List<int> nums = [1, 2, 3, 4, 5];
  bool hasEvenNumber = nums.any((int number) => number.isNaN);
  print('是否存在非數字: $hasEvenNumber');

  /*
    every方法用於檢查Iterable(例如List、Set)中的所有元素是否都滿足指定的條件。
    它接受一個函式作為參數,該函式對每個元素進行評估,並返回一個布林值,
    指示該元素是否滿足條件。
  */
  List<int> n2 = [2, 4, 6, 8, 10];
  bool allEven = n2.every((int number) => number.isEven);
  print('是否都是偶數: $allEven');

  print('3種遍歷 List的方法');
  List<int> lis = [21, 14, 53, 71];

  // forEach
  print('List.forEach');
  lis.forEach((int i) => print(i));

  // for next loop
  print('for next loop');
  for (int i = 0; i < lis.length; i++) {
    print(lis[i]);
  }

  // for in
  print('for in');
  for (int i in lis) {
    print(i);
  }

  // clear()
  lis.clear();
  print('List.clear(): $lis');

  print('Operators in List Map Set----------------');
  // spread operator ...
  var l1 = [2, 3];
  var l2 = [0, 1, ...l1, 4];
  print('spread operator ...\n$l2');

  var m = {'a': 123, 'b': 456};
  m = {...m, 'c': 789};
  print(m);

  // null-aware(null感知) spread operator ...?
  var ll1;
  var ll2 = [2, 3];
  var ll3 = [0, ...?ll1, 1, ...ll2, 4];
  print('null-aware spread operator ...?\n$ll3');

  // if
  var promoActive = false;
  var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];
  print(nav);

  var login = {"name": "asdf121472", "pw": '1234'};
  var kkk = [
    'Home',
    'Furniture',
    'Plants',
    if (login case Map<String, String>()) 'valid user'
  ];
  print(kkk);

  // for
  var i34 = [1, 2, 3];
  var i56 = ['# 0', for (var i in i34) '# $i'];
  print(i56);

  // 級聯..
  i56
    ..remove('# 2')
    ..remove('# 0');
  print(i56);
}