dart 学习列表 List

List 列表

在 Dart 编程语言中,List 是一种有序的集合数据类型,用于存储一系列项目。它允许您在单个变量中存储多个项目,并提供了许多操作来管理列表中的数据。以下是关于 Dart 中的 List 的一些重要信息:

  1. 创建 List:
    您可以使用以下方法之一来创建一个 List:

    // 创建一个空的 List
    List<int> emptyList = [];

    // 使用 List 构造函数创建 List
    List<String> fruits = List<String>();

    // 使用 List.of() 创建 List 并初始化数据
    List<int> numbers = List.of([1, 2, 3, 4, 5]);

    // 使用字面量创建 List
    List<double> decimalNumbers = [1.5, 2.0, 3.7];

  2. 基本操作:
    List 提供了许多方法来进行基本操作,如添加、移除、访问元素等。

    List<String> colors = ['red', 'green', 'blue'];

    // 获取列表长度
    int length = colors.length;

    // 访问元素
    String firstColor = colors[0];

    // 添加元素到列表末尾
    colors.add('yellow');

    // 在指定位置插入元素
    colors.insert(1, 'orange');

    // 删除指定元素
    colors.remove('green');

    // 删除指定索引位置的元素
    colors.removeAt(0);

    // 检查是否包含某元素
    bool hasBlue = colors.contains('blue');

    // 查找元素索引
    int indexOfBlue = colors.indexOf('blue');

  3. 迭代:
    您可以使用循环来遍历 List 中的元素。

    for (int i = 0; i < colors.length; i++) {
    print(colors[i]);
    }

    for (String color in colors) {
    print(color);
    }

    colors.forEach((color) {
    print(color);
    });
    4. 列表转换:
    List 可以通过 map、where 等方法进行转换。

    List<int> numbers = [1, 2, 3, 4, 5];

    List<int> doubledNumbers = numbers.map((number) => number * 2).toList();

    List<int> evenNumbers = numbers.where((number) => number % 2 == 0).toList();

  4. 排序:
    您可以使用 sort 方法对 List 进行排序。

    List<int> numbers = [4, 2, 1, 5, 3];
    numbers.sort(); // 默认升序排序

    List<String> words = ['apple', 'banana', 'cherry'];
    words.sort((a, b) => a.compareTo(b)); // 自定义排序

Dart 中的 List 是非常有用且常见的数据类型,适用于许多场景,从存储简单的数据到复杂的对象。它提供了丰富的方法来管理和操作列表中的数据,使您能够轻松处理各种数据集合。

相关推荐
sealaugh327 小时前
aws(学习笔记第四十八课) appsync-graphql-dynamodb
笔记·学习·aws
水木兰亭8 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
鱼摆摆拜拜8 小时前
第 3 章:神经网络如何学习
人工智能·神经网络·学习
aha-凯心8 小时前
vben 之 axios 封装
前端·javascript·学习
ytttr87311 小时前
matlab通过Q学习算法解决房间路径规划问题
学习·算法·matlab
听风ツ15 小时前
固高运动控制
学习
西岭千秋雪_15 小时前
Redis缓存架构实战
java·redis·笔记·学习·缓存·架构
XvnNing15 小时前
【Verilog硬件语言学习笔记4】FPGA串口通信
笔记·学习·fpga开发
牛奶咖啡1315 小时前
学习设计模式《十六》——策略模式
学习·设计模式·策略模式·认识策略模式·策略模式的优缺点·何时选用策略模式·策略模式的使用示例
The_cute_cat16 小时前
JavaScript的初步学习
开发语言·javascript·学习