Menu
CoddyTech

检查列表是否为空

本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 54 课,共 94 课。

isEmpty 和 isNotEmpty 属性可用于检查列表是否包含任何元素。这些属性会返回布尔值。

创建一个数字列表:

List<int> numbers = [1, 2, 3];
bool hasElements = !numbers.isEmpty;
print('List has elements: $hasElements');

执行上述代码后,输出为:

List has elements: true

创建一个空列表,并检查它是否为空:

List<String> emptyList = [];
bool isEmpty = emptyList.isEmpty;
print('List is empty: $isEmpty');

运行上述代码后,输出为:

List is empty: true

你也可以使用 isNotEmpty 属性:

bool hasItems = numbers.isNotEmpty;
print('List has items: $hasItems');

运行上面的代码后,输出将是:

List has items: true
challenge icon

挑战

入门

在这个挑战中,你将练习在 Dart 中检查列表是否为空。你可以使用 isEmpty 属性来检查列表是否不包含任何元素。

补全下面的代码,检查 shoppingList 是否为空。如果它为空,将 message 变量设为 "Your shopping list is empty!";否则,将它设为 "You have items in your shopping list!"

预期输出:

Your shopping list is empty!

亲手试试

void main() {
  // 这个购物列表已经为你定义好了
  List<String> shoppingList = [];
  
  // TODO: 检查 shoppingList 是否为空
  // 如果为空,将 message 设置为 "Your shopping list is empty!"
  // 否则,将 message 设置为 "You have items in your shopping list!"
  String message = "";
  
  // 这会显示结果
  print(message);
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Dart 在线编译器