リストが空かどうかのチェック
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チャレンジ
初心者このチャレンジでは、Dart でリストが空かどうかをチェックする練習をします。isEmpty プロパティを使用して、リストに要素が含まれていないかをチェックできます。
以下のコードを完成させて、shoppingList が空かどうかをチェックしてください。空の場合は、message 変数を "Your shopping list is empty!" に設定してください。そうでなければ、"You have items in your shopping list!" に設定してください。
期待される出力:
Your shopping list is empty!チートシート
isEmpty と isNotEmpty プロパティを使用して、リストに要素が含まれているかどうかを確認します。これらのプロパティは boolean 値を返します。
リストが空かどうかを確認:
List<String> emptyList = [];
bool isEmpty = emptyList.isEmpty;
print('List is empty: $isEmpty'); // List is empty: trueリストに要素があるかどうかを確認:
List<int> numbers = [1, 2, 3];
bool hasItems = numbers.isNotEmpty;
print('List has items: $hasItems'); // List has items: true否定を使用した代替方法:
bool hasElements = !numbers.isEmpty;自分で試してみよう
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);
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。