Flutter

Flutter에서 json 파일 사용하기 - dynamic to String

땅콩콩 2024. 2. 8. 17:46

Flutter 프로젝트 내부에서 json 파일을 사용할 때 값이 String이 아닌 dynamic으로 들어가면서 생긴 오류가 있었다.

{
   "01호선": [
        "중동",
        "도화",
        "간석",
        "개봉",
        "방학",
        "금정",
        "동암",
        "오산",
        // 등등
        ],
   "02호선": [
        "이대",
        "홍대입구",
        "건대입구",
        "구로디지털단지",
        "용두",
        "합정",
    ],
    // 등등...
}

 

내가 사용하고자 하는 json파일은 대충 이렇게 생겼다!

String jsonString = await rootBundle.loadString('asset/jsons/subway_stations.json');
final Map<String, dynamic> lineAndStations = json.decode(jsonString);

selectedLine = lineAndStations.keys.elementAt(0);
selectedStation = lineAndStations[selectedLine]![0];

 

저 json 파일을 이렇게 불러와서 코드에서 사용하고 있을 때,

DropdownButton(
    value: selectedStation,
    items: lineAndStations[selectedLine]!
        .map((e) => DropdownMenuItem(
      value: e.toString(),
      child: Text(e.toString()),
    ))
        .toList(),
    onChanged: (String? value) {
      setState(() {
        selectedStation = value!;
      });
    },
    ),

 

이렇게 map으로 dynamic값을 가져오면 타입 오류가 발생한다.

type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>?'

 

그래서 List<String> 으로 타입을 변환해줘야한다.

 

DropdownButton(
    value: selectedStation,
    items: List<String>.from(lineAndStations[selectedLine]!)
        .map((e) => DropdownMenuItem(
      value: e.toString(),
      child: Text(e.toString()),
    ))
        .toList(),
    onChanged: (String? value) {
      setState(() {
        selectedStation = value!;
      });
    },
    ),

 

이렇게 변환해주면 문제가 해결된다!