ram2 ๐Ÿš—

[Flutter] Using this in a constructor ์— ๋Œ€ํ•˜์—ฌ ๋ณธ๋ฌธ

๐Ÿ’ง flutter

[Flutter] Using this in a constructor ์— ๋Œ€ํ•˜์—ฌ

coram22 2022. 7. 6. 00:40
728x90
๋ฐ˜์‘ํ˜•

about using this in a constructor

this.propertyName ์€ ์งง๊ณ  ๊ฐ„๋‹จํ•˜๊ฒŒ constructor์˜ values์— ๊ฐ’์„ ํ• ๋‹นํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

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

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

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

์ œ์‹œ๋œ ์ฝ”๋“œ์—์„œ this.์€ class ๋ณ€์ˆ˜์— ๊ฐ’์„ ๋„ฃ๊ฒ ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค.
์ด๋Ÿฌํ•œ ๋ฐฉ์‹์€ named parameters์—์„œ๋„ ์‚ฌ์šฉ๋œ๋‹ค.

using this in named parameters

class MyColor {
  ...

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

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

์œ„ ์ฝ”๋“œ๋Š” MyColor์˜ parameters์— this๋ฅผ ์‚ฌ์šฉํ•œ ์˜ˆ์ด๋‹ค.
์—ฌ๊ธฐ์—๋Š” required๊ฐ€ ์‚ฌ์šฉ๋˜์—ˆ๋Š”๋ฐ, int values๋Š” null์ด ๋  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

  • ๋งŒ์•ฝ, ๊ฐ’์„ ์ง€์ •ํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” parameter๋ผ๋ฉด required๋ฅผ ์ƒ๋žตํ•ด๋„ ๋œ๋‹ค.

Question

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

์ฒซ ๋ฒˆ์งธ ์ฝ”๋“œ๋Š” ๋ฆฌ์ŠคํŠธ?
๋‘ ๋ฒˆ์งธ ์ฝ”๋“œ๋Š” property names๊ฐ€ parameters๊ฐ€ ๋  ์ˆ˜ ์žˆ์Œ์„ ๋ณด์—ฌ์ฃผ๋Š” ์˜ˆ.


Code example

class MyClass {
  final int anInt;
  final String aString;
  final double aDouble;
  
  // Create a constructor here.
}

Solution

class MyClass {
  final int anInt;
  final String aString;
  final double aDouble;
  
  MyClass(this.anInt, this.aString, this.aDouble);
}

์ฐธ๊ณ  ์‚ฌ์ดํŠธ: https://dart.dev/codelabs/dart-cheatsheet#initializer-lists

728x90
๋ฐ˜์‘ํ˜•

'๐Ÿ’ง flutter' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Flutter] FractionallySizedBox class ์ •๋ฆฌ  (0) 2022.07.06
[Flutter] FittedBox Class ์ •๋ฆฌ  (0) 2022.07.06
[Flutter] CustomSingleChildLayout ์ •๋ฆฌ  (0) 2022.07.06
[Flutter] Initializer lists ์ •๋ฆฌ  (0) 2022.07.06
[Flutter] Exceptions ์ด๋ž€!?  (0) 2022.07.06