zoukankan      html  css  js  c++  java
  • [Dart] Manipulate Lists/Arrays in Dart

    We will learn how to work with Lists using a variety of methods made available in the dart:core library. We will explore the top methods for working with List type collections.

    Learn more about Lists at https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html

    Array to list:

    because .map return iterable.

      var fruits = ['banana', 'pineapple', 'orange', 'watermelon', 'apple'];
      var fiboNumbers = [1, 2, 3, 5, 8, 13, 21];
      List<Map<String, dynamic>> users = [
        { 'name': 'John', 'age': 18 },
        { 'name': 'Jane', 'age': 21 },
        { 'name': 'Mary', 'age': 23 },
      ];
    
        // array to list
        var mappedFruits = fruits.map((fruit) => 'I love $fruit').toList();
        print(mappedFruits);

    reduce vs fold:

    reduce: doesn't provide the init value, but 'fold' does:

      const initialValue = 10;
      var sum2 = fiboNumbers.fold(initialValue, (curr, next) => curr + next);
      print( sum2 );
      
      var sum = fiboNumbers.reduce((curr, next) => curr + next);
      print( sum );

    filtering:

      var over21s = users.where((user) => user['age'] > 21);
      print( over21s.length );
      
      var nameJ = users.firstWhere((user) => user['name'].startsWith('J'), orElse: () => null);
      print( nameJ );
      
      var under18 = users.singleWhere((user) => user['age'] < 18, orElse: () => {'error': 'Not Found'});
      print( under18 );

    take & skip:

      print( fiboNumbers.take(3).toList() );
      print( fiboNumbers.skip(5).toList() );
      print( fiboNumbers.take(3).skip(2).take(1).toList() );

    expend: the same as flatMap in JS

      var flattened = [[1, 2], [3, 4]].expand((pair) => pair).toList();
      print( flattened );
      
      var duplicated = fiboNumbers.expand((i) => [i, i]).toList();
      print( duplicated );
  • 相关阅读:
    泛型为什么不用装箱拆箱
    net 自带cache
    泛型与非泛型的区别。
    java 魔术
    栈帧
    yii使用CUploadedFile上传文件
    yii上传图片、yii上传文件、yii控件activeFileField使用
    yii 验证码的使用
    mysql 分库分表
    全国省市区三级联动js
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11459398.html
Copyright © 2011-2022 走看看