メインコンテンツにスキップ

Dartチートシート

Dart言語は、他の言語から来たコーダーにとって学習しやすいように設計されていますが、いくつかのユニークな機能も備えています。このチュートリアルでは、これらの言語機能の中で最も重要なものについて説明します。

このチュートリアルに埋め込まれているエディタには、部分的にコードスニペットが入力されています。これらのエディタを使用して、コードを完成させて「実行」ボタンをクリックすることで、知識をテストできます。エディタには完全なテストコードも含まれています。テストコードは編集しないでくださいが、学習のために自由に参照してください。

ヘルプが必要な場合は、各DartPadの下にある「ソリューション」ドロップダウンを展開して、説明と回答を確認してください。

文字列補間

#

文字列内に式の値を挿入するには、${expression}を使用します。式が識別子である場合は、{}を省略できます。

文字列補間の使用例をいくつか示します

文字列結果
'${3 + 2}''5'
'${"word".toUpperCase()}''WORD'
'$myObject'myObject.toString()の値

演習

#

以下の関数は、2つの整数をパラメータとして受け取ります。それらをスペースで区切った文字列として返すようにします。たとえば、stringify(2, 3)'2 3'を返すはずです。

String stringify(int x, int y) {
  TODO('Return a formatted string here');
}


// Tests your solution (Don't edit!):
void main() {
  assert(stringify(2, 3) == '2 3',
      "Your stringify method returned '${stringify(2, 3)}' instead of '2 3'");
  print('Success!');
}
文字列補間例のソリューション

xyはどちらも単純な値であり、Dartの文字列補間はそれらを文字列表現に変換します。必要なのは、単一引用符内で$演算子を使用してそれらを参照し、間にスペースを入れることだけです。

dart
String stringify(int x, int y) {
  return '$x $y';
}

Nullable変数

#

Dartは厳格なnull安全性を強制します。これは、明示的に許可しない限り、値がnullであってはならないことを意味します。つまり、型はデフォルトで非nullableになります。

たとえば、次のコードを考えてみてください。null安全性があると、このコードはエラーを返します。int型の変数にnullの値を設定することはできません。

dart
int a = null; // INVALID.

変数を宣言するときは、型に?を追加して、変数がnullになりうることを示します。

dart
int? a = null; // Valid.

未初期化変数のデフォルト値は常にnullなので、すべてのDartバージョンでこのコードを少し簡略化できます。

dart
int? a; // The initial value of a is null.

Dartのnull安全性についてさらに学ぶには、厳格なnull安全性ガイドをお読みください。

演習

#

このDartPadで2つの変数を宣言します

  • 値が'Jane'のnullableString、名前はname
  • 値がnullのnullableString、名前はaddress

DartPadの初期エラーはすべて無視してください。

// TODO: Declare the two variables here


// Tests your solution (Don't edit!):
void main() {
  try {
    if (name == 'Jane' && address == null) {
      // Verify that "name" is nullable.
      name = null;
      print('Success!');
    } else {
      print('Not quite right, try again!');
    }
  } catch (e) {
    print('Exception: ${e.runtimeType}');
  }
}
Nullable変数例のソリューション

2つの変数をStringの後に?を付けて宣言します。次に、'Jane'nameに代入し、addressは初期化しないままにします。

dart
String? name = 'Jane';
String? address;

Null許容演算子

#

Dartは、nullの可能性がある値を扱うための便利な演算子を提供しています。1つは??=代入演算子で、変数が現在nullの場合にのみ値を変数に代入します。

dart
int? a; // = null
a ??= 3;
print(a); // <-- Prints 3.

a ??= 5;
print(a); // <-- Still prints 3.

もう1つのnull許容演算子は??で、左側の式を返しますが、その式の値がnullの場合は、右側の式を評価して返します。

dart
print(1 ?? 3); // <-- Prints 1.
print(null ?? 12); // <-- Prints 12.

演習

#

次のスニペットで、指定された動作を実装するために、??=??演算子を代入して試してみてください。

DartPadの初期エラーはすべて無視してください。

String? foo = 'a string';
String? bar; // = null

// Substitute an operator that makes 'a string' be assigned to baz.
String? baz = foo /* TODO */ bar;

void updateSomeVars() {
  // Substitute an operator that makes 'a string' be assigned to bar.
  bar /* TODO */ 'a string';
}


// Tests your solution (Don't edit!):
void main() {
  try {
    updateSomeVars();

    if (foo != 'a string') {
      print('Looks like foo somehow ended up with the wrong value.');
    } else if (bar != 'a string') {
      print('Looks like bar ended up with the wrong value.');
    } else if (baz != 'a string') {
      print('Looks like baz ended up with the wrong value.');
    } else {
      print('Success!');
    }
  } catch (e) {
    print('Exception: ${e.runtimeType}.');
  }
}
Null許容演算子例のソリューション

この演習で必要なのは、TODOコメントを??または??=に置き換えるだけです。両方を理解するために、上のテキストを読み、試してみてください。

dart
// Substitute an operator that makes 'a string' be assigned to baz.
String? baz = foo ?? bar;

void updateSomeVars() {
  // Substitute an operator that makes 'a string' be assigned to bar.
  bar ??= 'a string';
}

条件付きプロパティアクセス

#

nullの可能性があるオブジェクトのプロパティまたはメソッドへのアクセスを保護するには、ドット(.)の前に疑問符(?)を付けます。

dart
myObject?.someProperty

前のコードは、次のコードと同等です。

dart
(myObject != null) ? myObject.someProperty : null

?.を複数連鎖して1つの式で使用できます。

dart
myObject?.someProperty?.someMethod()

前のコードは、myObjectまたはmyObject.somePropertyのどちらかがnullの場合、nullを返します(そしてsomeMethod()は決して呼び出されません)。

演習

#

次の関数は、nullableな文字列をパラメータとして受け取ります。条件付きプロパティアクセスを使用して、strの大文字バージョン、またはstrnullの場合はnullを返すようにしてみてください。

String? upperCaseIt(String? str) {
  // TODO: Try conditionally accessing the `toUpperCase` method here.
}


// Tests your solution (Don't edit!):
void main() {
  try {
    String? one = upperCaseIt(null);
    if (one != null) {
      print('Looks like you\'re not returning null for null inputs.');
    } else {
      print('Success when str is null!');
    }
  } catch (e) {
    print('Tried calling upperCaseIt(null) and got an exception: \n ${e.runtimeType}.');
  }

  try {
    String? two = upperCaseIt('a string');
    if (two == null) {
      print('Looks like you\'re returning null even when str has a value.');
    } else if (two != 'A STRING') {
      print('Tried upperCaseIt(\'a string\'), but didn\'t get \'A STRING\' in response.');
    } else {
      print('Success when str is not null!');
    }
  } catch (e) {
    print('Tried calling upperCaseIt(\'a string\') and got an exception: \n ${e.runtimeType}.');
  }
}
条件付きプロパティアクセス例のソリューション

この演習で文字列を条件付きで小文字にする必要があった場合、次のように行うことができます: str?.toLowerCase()。文字列を大文字にするために同等のメソッドを使用してください!

dart
String? upperCaseIt(String? str) {
  return str?.toUpperCase();
}

コレクションリテラル

#

Dartは、リスト、マップ、セットをネイティブでサポートしています。リテラルを使用して作成できます。

dart
final aListOfStrings = ['one', 'two', 'three'];
final aSetOfStrings = {'one', 'two', 'three'};
final aMapOfStringsToInts = {'one': 1, 'two': 2, 'three': 3};

Dartの型推論により、これらの変数に型を自動的に割り当てることができます。この場合、推論される型はList<String>Set<String>、およびMap<String, int>です。

または、型を自分で指定することもできます。

dart
final aListOfInts = <int>[];
final aSetOfInts = <int>{};
final aMapOfIntToDouble = <int, double>{};

サブタイプのコンテンツでリストを初期化するが、リストはList<BaseType>のままである場合に、型を指定するのは便利です。

dart
final aListOfBaseType = <BaseType>[SubType(), SubType()];

演習

#

次の変数を指定された値に設定してみてください。既存のnull値を置き換えます。

// Assign this a list containing 'a', 'b', and 'c' in that order:
final aListOfStrings = null;

// Assign this a set containing 3, 4, and 5:
final aSetOfInts = null;

// Assign this a map of String to int so that aMapOfStringsToInts['myKey'] returns 12:
final aMapOfStringsToInts = null;

// Assign this an empty List<double>:
final anEmptyListOfDouble = null;

// Assign this an empty Set<String>:
final anEmptySetOfString = null;

// Assign this an empty Map of double to int:
final anEmptyMapOfDoublesToInts = null;


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  if (aListOfStrings is! List<String>) {
    errs.add('aListOfStrings should have the type List<String>.');
  } else if (aListOfStrings.length != 3) {
    errs.add('aListOfStrings has ${aListOfStrings.length} items in it, \n rather than the expected 3.');
  } else if (aListOfStrings[0] != 'a' || aListOfStrings[1] != 'b' || aListOfStrings[2] != 'c') {
    errs.add('aListOfStrings doesn\'t contain the correct values (\'a\', \'b\', \'c\').');
  }

  if (aSetOfInts is! Set<int>) {
    errs.add('aSetOfInts should have the type Set<int>.');
  } else if (aSetOfInts.length != 3) {
    errs.add('aSetOfInts has ${aSetOfInts.length} items in it, \n rather than the expected 3.');
  } else if (!aSetOfInts.contains(3) || !aSetOfInts.contains(4) || !aSetOfInts.contains(5)) {
    errs.add('aSetOfInts doesn\'t contain the correct values (3, 4, 5).');
  }

  if (aMapOfStringsToInts is! Map<String, int>) {
    errs.add('aMapOfStringsToInts should have the type Map<String, int>.');
  } else if (aMapOfStringsToInts['myKey'] != 12) {
    errs.add('aMapOfStringsToInts doesn\'t contain the correct values (\'myKey\': 12).');
  }

  if (anEmptyListOfDouble is! List<double>) {
    errs.add('anEmptyListOfDouble should have the type List<double>.');
  } else if (anEmptyListOfDouble.isNotEmpty) {
    errs.add('anEmptyListOfDouble should be empty.');
  }

  if (anEmptySetOfString is! Set<String>) {
    errs.add('anEmptySetOfString should have the type Set<String>.');
  } else if (anEmptySetOfString.isNotEmpty) {
    errs.add('anEmptySetOfString should be empty.');
  }

  if (anEmptyMapOfDoublesToInts is! Map<double, int>) {
    errs.add('anEmptyMapOfDoublesToInts should have the type Map<double, int>.');
  } else if (anEmptyMapOfDoublesToInts.isNotEmpty) {
    errs.add('anEmptyMapOfDoublesToInts should be empty.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }

  // ignore_for_file: unnecessary_type_check
}
コレクションリテラル例のソリューション

各等号(=)の後に、リスト、セット、またはマップリテラルを追加します。空の宣言には型を指定することを忘れないでください。推論できないためです。

dart
// Assign this a list containing 'a', 'b', and 'c' in that order:
final aListOfStrings = ['a', 'b', 'c'];

// Assign this a set containing 3, 4, and 5:
final aSetOfInts = {3, 4, 5};

// Assign this a map of String to int so that aMapOfStringsToInts['myKey'] returns 12:
final aMapOfStringsToInts = {'myKey': 12};

// Assign this an empty List<double>:
final anEmptyListOfDouble = <double>[];

// Assign this an empty Set<String>:
final anEmptySetOfString = <String>{};

// Assign this an empty Map of double to int:
final anEmptyMapOfDoublesToInts = <double, int>{};

アロー構文

#

Dartコードで=>記号を見たことがあるかもしれません。このアロー構文は、右側の式を実行してその値を返す関数を定義する方法です。

たとえば、Listクラスのany()メソッドのこの呼び出しを考えてみてください。

dart
bool hasEmpty = aListOfStrings.any((s) {
  return s.isEmpty;
});

このコードをよりシンプルに書く方法は次のとおりです。

dart
bool hasEmpty = aListOfStrings.any((s) => s.isEmpty);

演習

#

アロー構文を使用する次のステートメントを完成させてみてください。

class MyClass {
  int value1 = 2;
  int value2 = 3;
  int value3 = 5;

  // Returns the product of the above values:
  int get product => TODO();

  // Adds 1 to value1:
  void incrementValue1() => TODO();

  // Returns a string containing each item in the
  // list, separated by commas (e.g. 'a,b,c'):
  String joinWithCommas(List<String> strings) => TODO();
}


// Tests your solution (Don't edit!):
void main() {
  final obj = MyClass();
  final errs = <String>[];

  try {
    final product = obj.product;

    if (product != 30) {
      errs.add('The product property returned $product \n instead of the expected value (30).');
    }
  } catch (e) {
    print('Tried to use MyClass.product, but encountered an exception: \n ${e.runtimeType}.');
    return;
  }

  try {
    obj.incrementValue1();

    if (obj.value1 != 3) {
      errs.add('After calling incrementValue, value1 was ${obj.value1} \n instead of the expected value (3).');
    }
  } catch (e) {
    print('Tried to use MyClass.incrementValue1, but encountered an exception: \n ${e.runtimeType}.');
    return;
  }

  try {
    final joined = obj.joinWithCommas(['one', 'two', 'three']);

    if (joined != 'one,two,three') {
      errs.add('Tried calling joinWithCommas([\'one\', \'two\', \'three\']) \n and received $joined instead of the expected value (\'one,two,three\').');
    }
  } catch (e) {
    print('Tried to use MyClass.joinWithCommas, but encountered an exception: \n ${e.runtimeType}.');
    return;
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
アロー構文例のソリューション

積については、*を使用して3つの値を掛け合わせることができます。incrementValue1については、インクリメント演算子(++)を使用できます。joinWithCommasについては、Listクラスにあるjoinメソッドを使用します。

dart
class MyClass {
  int value1 = 2;
  int value2 = 3;
  int value3 = 5;

  // Returns the product of the above values:
  int get product => value1 * value2 * value3;

  // Adds 1 to value1:
  void incrementValue1() => value1++;

  // Returns a string containing each item in the
  // list, separated by commas (e.g. 'a,b,c'):
  String joinWithCommas(List<String> strings) => strings.join(',');
}

カスケード

#

同じオブジェクトに対して一連の操作を実行するには、カスケード(..)を使用します。このような式はすべて見たことがあるでしょう。

dart
myObject.someMethod()

これはmyObjectsomeMethod()を呼び出しますが、式の結果はsomeMethod()の戻り値です。

カスケードを使用した同じ式は次のとおりです。

dart
myObject..someMethod()

myObjectsomeMethod()を呼び出すことは依然として行われますが、式の結果は戻り値ではなくmyObjectへの参照です!

カスケードを使用すると、別々のステートメントを必要とした操作を連鎖させることができます。たとえば、buttonがnullでない場合にbuttonのプロパティを読み取るために条件付きメンバーアクセス演算子(?.)を使用する次のコードを考えてみてください。

dart
final button = web.document.querySelector('#confirm');
button?.textContent = 'Confirm';
button?.classList.add('important');
button?.onClick.listen((e) => web.window.alert('Confirmed!'));
button?.scrollIntoView();

代わりにカスケードを使用するには、*null短縮*カスケード(?..)から始めることができます。これは、nullオブジェクトに対してカスケード操作が試行されないことを保証します。カスケードを使用すると、コードが短縮され、button変数が不要になります。

dart
web.document.querySelector('#confirm')
  ?..textContent = 'Confirm'
  ..classList.add('important')
  ..onClick.listen((e) => web.window.alert('Confirmed!'))
  ..scrollIntoView();

演習

#

カスケードを使用して、BigObjectanIntaString、およびaListプロパティをそれぞれ1'String!'、および[3.0]に設定し、その後allDone()を呼び出す単一のステートメントを作成します。

class BigObject {
  int anInt = 0;
  String aString = '';
  List<double> aList = [];
  bool _done = false;

  void allDone() {
    _done = true;
  }
}

BigObject fillBigObject(BigObject obj) {
  // Create a single statement that will update and return obj:
  return TODO('obj..');
}


// Tests your solution (Don't edit!):
void main() {
  BigObject obj;

  try {
    obj = fillBigObject(BigObject());
  } catch (e) {
    print('Caught an exception of type ${e.runtimeType} \n while running fillBigObject');
    return;
  }

  final errs = <String>[];

  if (obj.anInt != 1) {
    errs.add(
        'The value of anInt was ${obj.anInt} \n rather than the expected (1).');
  }

  if (obj.aString != 'String!') {
    errs.add(
        'The value of aString was \'${obj.aString}\' \n rather than the expected (\'String!\').');
  }

  if (obj.aList.length != 1) {
    errs.add(
        'The length of aList was ${obj.aList.length} \n rather than the expected value (1).');
  } else {
    if (obj.aList[0] != 3.0) {
      errs.add(
          'The value found in aList was ${obj.aList[0]} \n rather than the expected (3.0).');
    }
  }

  if (!obj._done) {
    errs.add('It looks like allDone() wasn\'t called.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
カスケード例のソリューション

この演習の最良の解決策はobj..で始まり、4つの代入操作が連鎖しています。return obj..anInt = 1から始め、別のカスケード(..)を追加して次の代入を開始します。

dart
BigObject fillBigObject(BigObject obj) {
  return obj
    ..anInt = 1
    ..aString = 'String!'
    ..aList.add(3)
    ..allDone();
}

ゲッターとセッター

#

単純なフィールドでは許可されないプロパティの制御が必要な場合は、いつでもゲッターとセッターを定義できます。

たとえば、プロパティの値が有効であることを確認できます。

dart
class MyClass {
  int _aProperty = 0;

  int get aProperty => _aProperty;

  set aProperty(int value) {
    if (value >= 0) {
      _aProperty = value;
    }
  }
}

ゲッターを使用して計算プロパティを定義することもできます。

dart
class MyClass {
  final List<int> _values = [];

  void addValue(int value) {
    _values.add(value);
  }

  // A computed property.
  int get count {
    return _values.length;
  }
}

演習

#

価格のプライベートList<double>を保持するショッピングカートクラスを想像してみてください。以下を追加します。

  • 価格の合計を返すtotalという名前のゲッター。
  • 新しいリストでリストを置き換えるセッター。ただし、新しいリストに負の価格が含まれていない場合(その場合、セッターはInvalidPriceExceptionをスローする必要があります)。

DartPadの初期エラーはすべて無視してください。

class InvalidPriceException {}

class ShoppingCart {
  List<double> _prices = [];

  // TODO: Add a "total" getter here:

  // TODO: Add a "prices" setter here:
}


// Tests your solution (Don't edit!):
void main() {
  var foundException = false;

  try {
    final cart = ShoppingCart();
    cart.prices = [12.0, 12.0, -23.0];
  } on InvalidPriceException {
    foundException = true;
  } catch (e) {
    print('Tried setting a negative price and received a ${e.runtimeType} \n instead of an InvalidPriceException.');
    return;
  }

  if (!foundException) {
    print('Tried setting a negative price \n and didn\'t get an InvalidPriceException.');
    return;
  }

  final secondCart = ShoppingCart();

  try {
    secondCart.prices = [1.0, 2.0, 3.0];
  } catch(e) {
    print('Tried setting prices with a valid list, \n but received an exception: ${e.runtimeType}.');
    return;
  }

  if (secondCart._prices.length != 3) {
    print('Tried setting prices with a list of three values, \n but _prices ended up having length ${secondCart._prices.length}.');
    return;
  }

  if (secondCart._prices[0] != 1.0 || secondCart._prices[1] != 2.0 || secondCart._prices[2] != 3.0) {
    final vals = secondCart._prices.map((p) => p.toString()).join(', ');
    print('Tried setting prices with a list of three values (1, 2, 3), \n but incorrect ones ended up in the price list ($vals) .');
    return;
  }

  var sum = 0.0;

  try {
    sum = secondCart.total;
  } catch (e) {
    print('Tried to get total, but received an exception: ${e.runtimeType}.');
    return;
  }

  if (sum != 6.0) {
    print('After setting prices to (1, 2, 3), total returned $sum instead of 6.');
    return;
  }

  print('Success!');
}
ゲッターとセッター例のソリューション

この演習には2つの便利な関数があります。1つはリストを単一の値に減らすことができるfold(合計を計算するために使用します)。もう1つは、リストの各項目を渡された関数でチェックできるanypricesセッターで負の価格があるかどうかを確認するために使用します)。

dart
/// The total price of the shopping cart.
double get total => _prices.fold(0, (e, t) => e + t);

/// Set [prices] to the [value] list of item prices.
set prices(List<double> value) {
  if (value.any((p) => p < 0)) {
    throw InvalidPriceException();
  }

  _prices = value;
}

オプションの位置パラメータ

#

Dartには、位置パラメータと名前付きパラメータの2種類があります。位置パラメータは、おそらく熟悉的でしょう。

dart
int sumUp(int a, int b, int c) {
  return a + b + c;
}
  // ···
  int total = sumUp(1, 2, 3);

Dartでは、これらの位置パラメータを角括弧で囲むことでオプショナルにすることができます。

dart
int sumUpToFive(int a, [int? b, int? c, int? d, int? e]) {
  int sum = a;
  if (b != null) sum += b;
  if (c != null) sum += c;
  if (d != null) sum += d;
  if (e != null) sum += e;
  return sum;
}
  // ···
  int total = sumUpToFive(1, 2);
  int otherTotal = sumUpToFive(1, 2, 3, 4, 5);

オプショナルな位置パラメータは常に関数のパラメータリストの最後に配置されます。別のデフォルト値を提供しない限り、デフォルト値はnullです。

dart
int sumUpToFive(int a, [int b = 2, int c = 3, int d = 4, int e = 5]) {
  // ···
}

void main() {
  int newTotal = sumUpToFive(1);
  print(newTotal); // <-- prints 15
}

演習

#

1つから5つの整数を受け取り、それらの数値をカンマで区切った文字列を返すjoinWithCommas()という名前の関数を実装します。関数呼び出しと返される値の例をいくつか示します。

関数呼び出し返される値
joinWithCommas(1)'1'
joinWithCommas(1, 2, 3)'1,2,3'
joinWithCommas(1, 1, 1, 1, 1)'1,1,1,1,1'

String joinWithCommas(int a, [int? b, int? c, int? d, int? e]) {
  return TODO();
}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    final value = joinWithCommas(1);

    if (value != '1') {
      errs.add('Tried calling joinWithCommas(1) \n and got $value instead of the expected (\'1\').');
    }
  } on UnimplementedError {
    print('Tried to call joinWithCommas but failed. \n Did you implement the method?');
    return;
  } catch (e) {
    print('Tried calling joinWithCommas(1), \n but encountered an exception: ${e.runtimeType}.');
    return;
  }

  try {
    final value = joinWithCommas(1, 2, 3);

    if (value != '1,2,3') {
      errs.add('Tried calling joinWithCommas(1, 2, 3) \n and got $value instead of the expected (\'1,2,3\').');
    }
  } on UnimplementedError {
    print('Tried to call joinWithCommas but failed. \n Did you implement the method?');
    return;
  } catch (e) {
    print('Tried calling joinWithCommas(1, 2 ,3), \n but encountered an exception: ${e.runtimeType}.');
    return;
  }

  try {
    final value = joinWithCommas(1, 2, 3, 4, 5);

    if (value != '1,2,3,4,5') {
      errs.add('Tried calling joinWithCommas(1, 2, 3, 4, 5) \n and got $value instead of the expected (\'1,2,3,4,5\').');
    }
  } on UnimplementedError {
    print('Tried to call joinWithCommas but failed. \n Did you implement the method?');
    return;
  } catch (e) {
    print('Tried calling stringify(1, 2, 3, 4 ,5), \n but encountered an exception: ${e.runtimeType}.');
    return;
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
位置パラメータ例のソリューション

bcdeパラメータは、呼び出し元から提供されない場合はnullです。したがって、重要なのは、それらを最終的な文字列に追加する前に、それらの引数がnullであるかどうかを確認することです。

dart
String joinWithCommas(int a, [int? b, int? c, int? d, int? e]) {
  var total = '$a';
  if (b != null) total = '$total,$b';
  if (c != null) total = '$total,$c';
  if (d != null) total = '$total,$d';
  if (e != null) total = '$total,$e';
  return total;
}

名前付きパラメータ

#

パラメータリストの末尾の波括弧構文を使用して、名前が付いたパラメータを定義できます。

名前付きパラメータは、明示的にrequiredとマークされていない限りオプショナルです。

dart
void printName(String firstName, String lastName, {String? middleName}) {
  print('$firstName ${middleName ?? ''} $lastName');
}

void main() {
  printName('Dash', 'Dartisan');
  printName('John', 'Smith', middleName: 'Who');
  // Named arguments can be placed anywhere in the argument list.
  printName('John', middleName: 'Who', 'Smith');
}

予想されるように、nullableな名前付きパラメータのデフォルト値はnullですが、カスタムデフォルト値を提供できます。

パラメータの型がnon-nullableの場合、デフォルト値を提供するか(次のコードに示すように)、パラメータをrequiredとマークする(*コンストラクタ*セクションに示すように)必要があります。

dart
void printName(String firstName, String lastName, {String middleName = ''}) {
  print('$firstName $middleName $lastName');
}

関数は、オプショナルな位置パラメータと名前付きパラメータの両方を持つことはできません。

演習

#

MyDataObjectクラスにcopyWith()インスタンスメソッドを追加します。3つのnullableな名前付きパラメータを受け取る必要があります。

  • int? newInt
  • String? newString
  • double? newDouble

copyWith()メソッドは、現在のインスタンスに基づいて新しいMyDataObjectを返す必要があります。前のパラメータからのデータがオブジェクトのプロパティにコピーされます(もしあれば)。たとえば、newIntがnon-nullの場合、その値をanIntにコピーします。

DartPadの初期エラーはすべて無視してください。

class MyDataObject {
  final int anInt;
  final String aString;
  final double aDouble;

  MyDataObject({
     this.anInt = 1,
     this.aString = 'Old!',
     this.aDouble = 2.0,
  });

  // TODO: Add your copyWith method here:
}


// Tests your solution (Don't edit!):
void main() {
  final source = MyDataObject();
  final errs = <String>[];

  try {
    final copy = source.copyWith(newInt: 12, newString: 'New!', newDouble: 3.0);

    if (copy.anInt != 12) {
      errs.add('Called copyWith(newInt: 12, newString: \'New!\', newDouble: 3.0), \n and the new object\'s anInt was ${copy.anInt} rather than the expected value (12).');
    }

    if (copy.aString != 'New!') {
      errs.add('Called copyWith(newInt: 12, newString: \'New!\', newDouble: 3.0), \n and the new object\'s aString was ${copy.aString} rather than the expected value (\'New!\').');
    }

    if (copy.aDouble != 3) {
      errs.add('Called copyWith(newInt: 12, newString: \'New!\', newDouble: 3.0), \n and the new object\'s aDouble was ${copy.aDouble} rather than the expected value (3).');
    }
  } catch (e) {
    print('Called copyWith(newInt: 12, newString: \'New!\', newDouble: 3.0) \n and got an exception: ${e.runtimeType}');
  }

  try {
    final copy = source.copyWith();

    if (copy.anInt != 1) {
      errs.add('Called copyWith(), and the new object\'s anInt was ${copy.anInt} \n rather than the expected value (1).');
    }

    if (copy.aString != 'Old!') {
      errs.add('Called copyWith(), and the new object\'s aString was ${copy.aString} \n rather than the expected value (\'Old!\').');
    }

    if (copy.aDouble != 2) {
      errs.add('Called copyWith(), and the new object\'s aDouble was ${copy.aDouble} \n rather than the expected value (2).');
    }
  } catch (e) {
    print('Called copyWith() and got an exception: ${e.runtimeType}');
  }

  try {
    final sourceWithoutDefaults = MyDataObject(
      anInt: 520,
      aString: 'Custom!',
      aDouble: 20.25,
    );
    final copy = sourceWithoutDefaults.copyWith();

    if (copy.anInt == 1) {
      errs.add('Called `copyWith()` on an object with a non-default `anInt` value (${sourceWithoutDefaults.anInt}), but the new object\'s `anInt` was the default value of ${copy.anInt}.');
    }

    if (copy.aString == 'Old!') {
      errs.add('Called `copyWith()` on an object with a non-default `aString` value (\'${sourceWithoutDefaults.aString}\'), but the new object\'s `aString` was the default value of \'${copy.aString}\'.');
    }

    if (copy.aDouble == 2.0) {
      errs.add('Called copyWith() on an object with a non-default `aDouble` value (${sourceWithoutDefaults.aDouble}), but the new object\'s `aDouble` was the default value of ${copy.aDouble}.');
    }
  } catch (e) {
    print('Called copyWith() and got an exception: ${e.runtimeType}');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
名前付きパラメータ例のソリューション

copyWithメソッドは、多くのクラスやライブラリに登場します。あなたのものも同様の機能を持つべきです: オプショナルな名前付きパラメータを使用し、新しいMyDataObjectインスタンスを作成し、パラメータのデータ(またはパラメータがnullの場合は現在のインスタンスのデータ)を使用してそれを埋めます。これは??演算子でさらに練習する機会です!

dart
MyDataObject copyWith({int? newInt, String? newString, double? newDouble}) {
  return MyDataObject(
    anInt: newInt ?? this.anInt,
    aString: newString ?? this.aString,
    aDouble: newDouble ?? this.aDouble,
  );
}

例外

#

Dartコードは例外をスローおよびキャッチできます。Javaとは異なり、Dartの例外はすべてチェックされていません。メソッドはスローする可能性のある例外を宣言せず、例外をキャッチする必要もありません。

DartはExceptionError型を提供しますが、nullでない任意のオブジェクトをスローできます。

dart
throw Exception('Something bad happened.');
throw 'Waaaaaaah!';

例外処理にはtryoncatchキーワードを使用します。

dart
try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

tryキーワードは、ほとんどの他の言語と同様に機能します。onキーワードは型で特定の例外をフィルタリングするために使用され、catchキーワードは例外オブジェクトへの参照を取得するために使用されます。

例外を完全に処理できない場合は、rethrowキーワードを使用して例外を伝播させます。

dart
try {
  breedMoreLlamas();
} catch (e) {
  print('I was just trying to breed llamas!');
  rethrow;
}

例外がスローされたかどうかに関わらずコードを実行するには、finallyを使用します。

dart
try {
  breedMoreLlamas();
} catch (e) {
  // ... handle exception ...
} finally {
  // Always clean up, even if an exception is thrown.
  cleanLlamaStalls();
}

演習

#

以下のtryFunction()を実装します。信頼できないメソッドを実行し、次のことを行う必要があります。

  • untrustworthy()ExceptionWithMessageをスローした場合、例外の型とメッセージでlogger.logExceptionを呼び出します(oncatchを使用してみてください)。
  • untrustworthy()Exceptionをスローした場合、例外の型でlogger.logExceptionを呼び出します(この場合はonを使用してみてください)。
  • untrustworthy()が他のオブジェクトをスローした場合、例外をキャッチしないでください。
  • すべてがキャッチされ、処理された後、logger.doneLoggingを呼び出します(finallyを使用してみてください)。
typedef VoidFunction = void Function();

class ExceptionWithMessage {
  final String message;
  const ExceptionWithMessage(this.message);
}

// Call logException to log an exception, and doneLogging when finished.
abstract class Logger {
  void logException(Type t, [String? msg]);
  void doneLogging();
}

void tryFunction(VoidFunction untrustworthy, Logger logger) {
  try {
    untrustworthy();
  } // Write your logic here
}

// Tests your solution (Don't edit!):
class MyLogger extends Logger {
  Type? lastType;
  String lastMessage = '';
  bool done = false;

  void logException(Type t, [String? message]) {
    lastType = t;
    lastMessage = message ?? lastMessage;
  }

  void doneLogging() => done = true;
}

void main() {
  final errs = <String>[];
  var logger = MyLogger();

  try {
    tryFunction(() => throw Exception(), logger);

    if ('${logger.lastType}' != 'Exception' && '${logger.lastType}' != '_Exception') {
      errs.add('Untrustworthy threw an Exception, but a different type was logged: \n ${logger.lastType}.');
    }

    if (logger.lastMessage != '') {
      errs.add('Untrustworthy threw an Exception with no message, but a message \n was logged anyway: \'${logger.lastMessage}\'.');
    }

    if (!logger.done) {
      errs.add('Untrustworthy threw an Exception, \n and doneLogging() wasn\'t called afterward.');
    }
  } catch (e) {
    print('Untrustworthy threw an exception, and an exception of type \n ${e.runtimeType} was unhandled by tryFunction.');
  }

  logger = MyLogger();

  try {
    tryFunction(() => throw ExceptionWithMessage('Hey!'), logger);

    if (logger.lastType != ExceptionWithMessage) {
      errs.add('Untrustworthy threw an ExceptionWithMessage(\'Hey!\'), but a \n different type was logged: ${logger.lastType}.');
    }

    if (logger.lastMessage != 'Hey!') {
      errs.add('Untrustworthy threw an ExceptionWithMessage(\'Hey!\'), but a \n different message was logged: \'${logger.lastMessage}\'.');
    }

    if (!logger.done) {
      errs.add('Untrustworthy threw an ExceptionWithMessage(\'Hey!\'), \n and doneLogging() wasn\'t called afterward.');
    }
  } catch (e) {
    print('Untrustworthy threw an ExceptionWithMessage(\'Hey!\'), \n and an exception of type ${e.runtimeType} was unhandled by tryFunction.');
  }

  logger = MyLogger();
  bool caughtStringException = false;

  try {
    tryFunction(() => throw 'A String', logger);
  } on String {
    caughtStringException = true;
  }

  if (!caughtStringException) {
    errs.add('Untrustworthy threw a string, and it was incorrectly handled inside tryFunction().');
  }

  logger = MyLogger();

  try {
    tryFunction(() {}, logger);

    if (logger.lastType != null) {
      errs.add('Untrustworthy didn\'t throw an Exception, \n but one was logged anyway: ${logger.lastType}.');
    }

    if (logger.lastMessage != '') {
      errs.add('Untrustworthy didn\'t throw an Exception with no message, \n but a message was logged anyway: \'${logger.lastMessage}\'.');
    }

    if (!logger.done) {
      errs.add('Untrustworthy didn\'t throw an Exception, \n but doneLogging() wasn\'t called afterward.');
    }
  } catch (e) {
    print('Untrustworthy didn\'t throw an exception, \n but an exception of type ${e.runtimeType} was unhandled by tryFunction anyway.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
例外例のソリューション

この演習は難しそうに見えますが、実際には1つの大きなtryステートメントです。try内でuntrustworthyを呼び出し、次にoncatchfinallyを使用して例外をキャッチし、ロガーのメソッドを呼び出します。

dart
void tryFunction(VoidFunction untrustworthy, Logger logger) {
  try {
    untrustworthy();
  } on ExceptionWithMessage catch (e) {
    logger.logException(e.runtimeType, e.message);
  } on Exception {
    logger.logException(Exception);
  } finally {
    logger.doneLogging();
  }
}

コンストラクタでのthisの使用

#

Dartは、コンストラクタでプロパティに値を代入するための便利なショートカットを提供します。コンストラクタを宣言するときにthis.propertyNameを使用します。

dart
class MyColor {
  int red;
  int green;
  int blue;

  MyColor(this.red, this.green, this.blue);
}

final color = MyColor(80, 80, 128);

このテクニックは名前付きパラメータにも有効です。プロパティ名がパラメータ名になります。

dart
class MyColor {
  // ...

  MyColor({required this.red, required this.green, required this.blue});
}

final color = MyColor(red: 80, green: 80, blue: 80);

前のコードでは、redgreenbluerequiredとマークされています。これらのint値はnullにできないためです。デフォルト値を追加すると、requiredを省略できます。

dart
MyColor([this.red = 0, this.green = 0, this.blue = 0]);
// or
MyColor({this.red = 0, this.green = 0, this.blue = 0});

演習

#

MyClassに1行のコンストラクタを追加します。これはthis.構文を使用して、クラスの3つのプロパティすべてを受け取り、代入します。

DartPadの初期エラーはすべて無視してください。

class MyClass {
  final int anInt;
  final String aString;
  final double aDouble;

  // TODO: Create the constructor here.
}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    final obj = MyClass(1, 'two', 3);

    if (obj.anInt != 1) {
      errs.add('Called MyClass(1, \'two\', 3) and got an object with anInt of ${obj.anInt} \n instead of the expected value (1).');
    }

    if (obj.anInt != 1) {
      errs.add('Called MyClass(1, \'two\', 3) and got an object with aString of \'${obj.aString}\' \n instead of the expected value (\'two\').');
    }

    if (obj.anInt != 1) {
      errs.add('Called MyClass(1, \'two\', 3) and got an object with aDouble of ${obj.aDouble} \n instead of the expected value (3).');
    }
  } catch (e) {
    print('Called MyClass(1, \'two\', 3) and got an exception \n of type ${e.runtimeType}.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
this例のソリューション

この演習の解決策は1行です。コンストラクタをthis.anIntthis.aStringthis.aDoubleをパラメータとして、その順序で宣言します。

dart
MyClass(this.anInt, this.aString, this.aDouble);

初期化子リスト

#

コンストラクタを実装するときに、コンストラクタ本体が実行される前にセットアップを行う必要がある場合があります。たとえば、finalフィールドはコンストラクタ本体が実行される前に値を持つ必要があります。この作業は、コンストラクタのシグネチャとその本体の間にある初期化子リストで行います。

dart
Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! {
  print('In Point.fromJson(): ($x, $y)');
}

初期化子リストは、アサートを配置するのに便利な場所でもあります。アサートは開発中にのみ実行されます。

dart
NonNegativePoint(this.x, this.y) : assert(x >= 0), assert(y >= 0) {
  print('I just made a NonNegativePoint: ($x, $y)');
}

演習

#

以下のFirstTwoLettersコンストラクタを完成させてください。初期化子リストを使用して、wordの最初の2文字をletterOneLetterTwoプロパティに代入します。追加のボーナスとして、2文字未満の単語をキャッチするassertを追加します。

DartPadの初期エラーはすべて無視してください。

class FirstTwoLetters {
  final String letterOne;
  final String letterTwo;

  // TODO: Create a constructor with an initializer list here:
  FirstTwoLetters(String word)

}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    final result = FirstTwoLetters('My String');

    if (result.letterOne != 'M') {
      errs.add('Called FirstTwoLetters(\'My String\') and got an object with \n letterOne equal to \'${result.letterOne}\' instead of the expected value (\'M\').');
    }

    if (result.letterTwo != 'y') {
      errs.add('Called FirstTwoLetters(\'My String\') and got an object with \n letterTwo equal to \'${result.letterTwo}\' instead of the expected value (\'y\').');
    }
  } catch (e) {
    errs.add('Called FirstTwoLetters(\'My String\') and got an exception \n of type ${e.runtimeType}.');
  }

  bool caughtException = false;

  try {
    FirstTwoLetters('');
  } catch (e) {
    caughtException = true;
  }

  if (!caughtException) {
    errs.add('Called FirstTwoLetters(\'\') and didn\'t get an exception \n from the failed assertion.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
初期化子リスト例のソリューション

2つの代入が必要です: letterOneにはword[0]を代入し、letterTwoにはword[1]を代入します。

dart
  FirstTwoLetters(String word)
      : assert(word.length >= 2),
        letterOne = word[0],
        letterTwo = word[1];

名前付きコンストラクタ

#

クラスに複数のコンストラクタを持たせるために、Dartは名前付きコンストラクタをサポートしています。

dart
class Point {
  double x, y;

  Point(this.x, this.y);

  Point.origin() : x = 0, y = 0;
}

名前付きコンストラクタを使用するには、完全な名前で呼び出します。

dart
final myPoint = Point.origin();

演習

#

ColorクラスにColor.blackという名前のコンストラクタを作成し、すべての3つのプロパティをゼロに設定します。

DartPadの初期エラーはすべて無視してください。

class Color {
  int red;
  int green;
  int blue;

  Color(this.red, this.green, this.blue);

  // TODO: Create a named constructor called "Color.black" here:
}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    final result = Color.black();

    if (result.red != 0) {
      errs.add('Called Color.black() and got a Color with red equal to \n ${result.red} instead of the expected value (0).');
    }

    if (result.green != 0) {
      errs.add('Called Color.black() and got a Color with green equal to \n ${result.green} instead of the expected value (0).');
    }

    if (result.blue != 0) {
  errs.add('Called Color.black() and got a Color with blue equal to \n ${result.blue} instead of the expected value (0).');
    }
  } catch (e) {
    print('Called Color.black() and got an exception of type \n ${e.runtimeType}.');
    return;
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
名前付きコンストラクタ例のソリューション

コンストラクタの宣言はColor.black():で始める必要があります。初期化子リスト(コロンの後)で、redgreenblue0に設定します。

dart
Color.black() : red = 0, green = 0, blue = 0;

ファクトリコンストラクタ

#

Dartはファクトリコンストラクタをサポートしており、サブタイプやnullを返すことができます。ファクトリコンストラクタを作成するには、factoryキーワードを使用します。

dart
class Square extends Shape {}

class Circle extends Shape {}

class Shape {
  Shape();

  factory Shape.fromTypeName(String typeName) {
    if (typeName == 'square') return Square();
    if (typeName == 'circle') return Circle();

    throw ArgumentError('Unrecognized $typeName');
  }
}

演習

#

IntegerHolder.fromListという名前のファクトリコンストラクタのTODO();行を、次の値を返すように置き換えます。

  • リストに値が1つある場合、その値を使用してIntegerSingleインスタンスを作成します。
  • リストに値が2つある場合、順序で値を使用してIntegerDoubleインスタンスを作成します。
  • リストに値が3つある場合、順序で値を使用してIntegerTripleインスタンスを作成します。
  • それ以外の場合は、Errorをスローします。

成功した場合、コンソールにSuccess!と表示されます。

class IntegerHolder {
  IntegerHolder();

  // Implement this factory constructor.
  factory IntegerHolder.fromList(List<int> list) {
    TODO();
  }
}

class IntegerSingle extends IntegerHolder {
  final int a;

  IntegerSingle(this.a);
}

class IntegerDouble extends IntegerHolder {
  final int a;
  final int b;

  IntegerDouble(this.a, this.b);
}

class IntegerTriple extends IntegerHolder {
  final int a;
  final int b;
  final int c;

  IntegerTriple(this.a, this.b, this.c);
}

// Tests your solution (Don't edit from this point to end of file):
void main() {
  final errs = <String>[];

  // Run 5 tests to see which values have valid integer holders.
  for (var tests = 0; tests < 5; tests++) {
    if (!testNumberOfArgs(errs, tests)) return;
  }

  // The goal is no errors with values 1 to 3,
  // but have errors with values 0 and 4.
  // The testNumberOfArgs method adds to the errs array if
  // the values 1 to 3 have an error and
  // the values 0 and 4 don't have an error.
  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}

bool testNumberOfArgs(List<String> errs, int count) {
  bool _threw = false;
  final ex = List.generate(count, (index) => index + 1);
  final callTxt = "IntegerHolder.fromList(${ex})";
  try {
    final obj = IntegerHolder.fromList(ex);
    final String vals = count == 1 ? "value" : "values";
    // Uncomment the next line if you want to see the results realtime
    // print("Testing with ${count} ${vals} using ${obj.runtimeType}.");
    testValues(errs, ex, obj, callTxt);
  } on Error {
    _threw = true;
  } catch (e) {
    switch (count) {
      case (< 1 && > 3):
        if (!_threw) {
          errs.add('Called ${callTxt} and it didn\'t throw an Error.');
        }
      default:
        errs.add('Called $callTxt and received an Error.');
    }
  }
  return true;
}

void testValues(List<String> errs, List<int> expectedValues, IntegerHolder obj,
    String callText) {
  for (var i = 0; i < expectedValues.length; i++) {
    int found;
    if (obj is IntegerSingle) {
      found = obj.a;
    } else if (obj is IntegerDouble) {
      found = i == 0 ? obj.a : obj.b;
    } else if (obj is IntegerTriple) {
      found = i == 0
          ? obj.a
          : i == 1
              ? obj.b
              : obj.c;
    } else {
      throw ArgumentError(
          "This IntegerHolder type (${obj.runtimeType}) is unsupported.");
    }

    if (found != expectedValues[i]) {
      errs.add(
          "Called $callText and got a ${obj.runtimeType} " +
          "with a property at index $i value of $found " +
          "instead of the expected (${expectedValues[i]}).");
    }
  }
}
ファクトリコンストラクタ例のソリューション

ファクトリコンストラクタ内で、リストの長さをチェックし、必要に応じてIntegerSingleIntegerDouble、またはIntegerTripleを作成して返します。

TODO();を次のコードブロックで置き換えます。

dart
  switch (list.length) {
    case 1:
      return IntegerSingle(list[0]);
    case 2:
      return IntegerDouble(list[0], list[1]);
    case 3:
      return IntegerTriple(list[0], list[1], list[2]);
    default:
      throw ArgumentError("List must between 1 and 3 items. This list was ${list.length} items.");
  }

リダイレクトコンストラクタ

#

コンストラクタの唯一の目的が、同じクラスの別のコンストラクタにリダイレクトすることである場合があります。リダイレクトコンストラクタの本体は空で、コンストラクタの呼び出しはコロン(:)の後に表示されます。

dart
class Automobile {
  String make;
  String model;
  int mpg;

  // The main constructor for this class.
  Automobile(this.make, this.model, this.mpg);

  // Delegates to the main constructor.
  Automobile.hybrid(String make, String model) : this(make, model, 60);

  // Delegates to a named constructor
  Automobile.fancyHybrid() : this.hybrid('Futurecar', 'Mark 2');
}

演習

#

前のColorクラスを覚えていますか?blackという名前のコンストラクタを作成しますが、プロパティを手動で代入する代わりに、ゼロを引数としてデフォルトコンストラクタにリダイレクトします。

DartPadの初期エラーはすべて無視してください。

class Color {
  int red;
  int green;
  int blue;

  Color(this.red, this.green, this.blue);

  // TODO: Create a named constructor called "black" here
  // and redirect it to call the existing constructor
}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    final result = Color.black();

    if (result.red != 0) {
      errs.add('Called Color.black() and got a Color with red equal to \n ${result.red} instead of the expected value (0).');
    }

    if (result.green != 0) {
      errs.add('Called Color.black() and got a Color with green equal to \n ${result.green} instead of the expected value (0).');
    }

    if (result.blue != 0) {
  errs.add('Called Color.black() and got a Color with blue equal to \n ${result.blue} instead of the expected value (0).');
    }
  } catch (e) {
    print('Called Color.black() and got an exception of type ${e.runtimeType}.');
    return;
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
リダイレクトコンストラクタ例のソリューション

コンストラクタはthis(0, 0, 0)にリダイレクトする必要があります。

dart
Color.black() : this(0, 0, 0);

constコンストラクタ

#

クラスが変更されないオブジェクトを生成する場合、それらのオブジェクトをコンパイル時定数にすることができます。これを行うには、constコンストラクタを定義し、すべてのインスタンス変数がfinalであることを確認します。

dart
class ImmutablePoint {
  static const ImmutablePoint origin = ImmutablePoint(0, 0);

  final int x;
  final int y;

  const ImmutablePoint(this.x, this.y);
}

演習

#

Recipeクラスを、そのインスタンスが定数になるように変更し、次のことを行う定数コンストラクタを作成します。

  • 3つのパラメータがあります: ingredientscaloriesmilligramsOfSodium(その順序)。
  • this.構文を使用して、パラメータ値を同じ名前のオブジェクトプロパティに自動的に代入します。
  • 定数であり、コンストラクタ宣言のRecipeの直前にconstキーワードが付いています。

DartPadの初期エラーはすべて無視してください。

class Recipe {
  List<String> ingredients;
  int calories;
  double milligramsOfSodium;

  // TODO: Create a const constructor here.

}


// Tests your solution (Don't edit!):
void main() {
  final errs = <String>[];

  try {
    const obj = Recipe(['1 egg', 'Pat of butter', 'Pinch salt'], 120, 200);

    if (obj.ingredients.length != 3) {
      errs.add('Called Recipe([\'1 egg\', \'Pat of butter\', \'Pinch salt\'], 120, 200) \n and got an object with ingredient list of length ${obj.ingredients.length} rather than the expected length (3).');
    }

    if (obj.calories != 120) {
      errs.add('Called Recipe([\'1 egg\', \'Pat of butter\', \'Pinch salt\'], 120, 200) \n and got an object with a calorie value of ${obj.calories} rather than the expected value (120).');
    }

    if (obj.milligramsOfSodium != 200) {
      errs.add('Called Recipe([\'1 egg\', \'Pat of butter\', \'Pinch salt\'], 120, 200) \n and got an object with a milligramsOfSodium value of ${obj.milligramsOfSodium} rather than the expected value (200).');
    }

    try {
      obj.ingredients.add('Sugar to taste');
      errs.add('Tried adding an item to the \'ingredients\' list of a const Recipe and didn\'t get an error due to it being unmodifiable.');
    } on UnsupportedError catch (_) {
      // We expect an `UnsupportedError` due to
      // `ingredients` being a const, unmodifiable list.
    }
  } catch (e) {
    print('Tried calling Recipe([\'1 egg\', \'Pat of butter\', \'Pinch salt\'], 120, 200) \n and received a null.');
  }

  if (errs.isEmpty) {
    print('Success!');
  } else {
    errs.forEach(print);
  }
}
constコンストラクタ例のソリューション

コンストラクタをconstにするには、すべてのプロパティをfinalにする必要があります。

dart
class Recipe {
  final List<String> ingredients;
  final int calories;
  final double milligramsOfSodium;

  const Recipe(this.ingredients, this.calories, this.milligramsOfSodium);
}

次は何?

#

このチュートリアルを使用して、Dart言語の最も興味深い機能のいくつかを学習またはテストしていただいたことを願っています。

次に試せることには以下が含まれます。