Search

[dart] type casting + optional chaining

subtitle
dart ํƒ€์ž… ์บ์ŠคํŒ…, ์˜ต์…”๋„ ์ฒด์ด๋‹
Created
2021/02/25 15:53
tags
dart
source: google image

type 'A' is not a subtype of type 'B'

์•„๋ž˜์™€ ๊ฐ™์€ ์˜ค๋ฅ˜๊ฐ€ ๋œฌ๋‹ค.
final List<String> authors = json['authors'] // ์—๋Ÿฌ => type 'List<dynamic>' is not a subtype of type 'List<String>'
Dart
๋ณต์‚ฌ
json['authors'].runtimeType ์„ ๋กœ๊น…ํ•ด์„œ ๋ดค๋”๋‹ˆ List<dynamic> ์ด๋ผ๊ณ  ๋–ด๋‹ค. ๋งŒ์•ฝ ์‹ค์ œ๋กœ String ํƒ€์ž…์ด ์˜ค๊ณ  dart๊ฐ€ ์ด๋ฅผ ๋ชจ๋ฅด๋Š” ์ƒํ™ฉ์ด๋ผ๋ฉด ํƒ€์ž… ์บ์ŠคํŒ…์„ ์œ„ํ•ด ์•„๋ž˜์ฒ˜๋Ÿผ ๋ฐ”๊ฟ”์ฃผ๋ฉด ๋œ๋‹ค.
(ํ•˜์ง€๋งŒ ํƒ€์ž…์ด ์ •๋ง ๋‹ค๋ฅธ ๊ฒฝ์šฐ๋Š” ๋˜‘๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒƒ์ด๋‹ค.)

optional chaining

optional chaining์€ null์ด ์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฐ์ฒด๋ผ๋ฉด, null์ด ์•„๋‹ ๋•Œ๋งŒ ๊ทธ ์•ˆ์˜ method๋‚˜ ๊ฐ’์„ ๊บผ๋‚ผ ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ๊ฒƒ์ด๋‹ค.
์˜ˆ๋ฅผ ๋“ค์–ด ํƒ€์ž… ์บ์ŠคํŒ…ํ•˜๋ ค๋Š” ๊ฐ์ฒด๊ฐ€ null์ด ๋  ์ˆ˜ ์žˆ๋‹ค๋ฉด, ๊ฐ์ฒด์— optional chaining ?. ์„ ๋ถ™์—ฌ null์ด ์•„๋‹Œ ๊ฒฝ์šฐ์— cast ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.
final List<String> authors = json['authors']?.cast<String>()
Dart
๋ณต์‚ฌ

references