LoginSignup
0
0

More than 3 years have passed since last update.

DartでMapにスプレッドを使って条件次第で値を追加する

Last updated at Posted at 2021-02-14

Dartについてのメモ。

DartでMapにスプレッドを使って条件次第で値を追加する方法。

void main() {
  bool test = false;
  Map<String, String> myMapA = {
    "a": "1",
    "b": "2",
   ... test == true ? {"c":"3"} : {}
  };
  Map<String, String> myMapB = {
    "a": "1",
    "b": "2",
   ... test == false ? {"c":"3"} : {}
  };

  print(myMapA);
  print(myMapB);
}

実行結果:

{a: 1, b: 2}
{a: 1, b: 2, c: 3}

Javascriptでも似た様な事が出来るけど、dartのMapはJavascriptではObject{}の代わりにnullが使える。Dartではnullを代わりに代入しようとしたら、エラーが出てしまう。また、javascriptの===が、dartでは==になる。

let test = false;
const myMapA = {
  a: '1',
  b: '2',
  ...(test === true ? { c: '3' } : null),
};
const myMapB = {
  a: '1',
  b: '2',
  ...(test === false ? { c: '3' } : null),
};

console.log(myMapA);
console.log(myMapB);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0