• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    미해결

firestore에서 List<String>을 받아오고 싶을 때

23.02.06 16:30 작성 23.02.06 16:32 수정 조회수 361

0

안녕하세요. 강의를 따라 오던 중 복수의 이미지 리스트 List<String>으로 업로드하고 또 읽어올 수 있을지 궁금증이 생겨 테스트를 하던 중 도저히 해결되지 않은 문제가 있어 질문 올립니다.(업로드는 성공했습니다.)

현재 강의 코드에서 imageUrlString에서 List<String>으로 바꿔 아래와 같이 수정했습니다.

class Post {
  String id;
  String userId;
  String title;
  List<String> imageUrls;

  Post({
    required this.id,
    required this.userId,
    required this.title,
    required this.imageUrls,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] as String,
      userId: json['userId'] as String,
      title: json['title'] as String,
      imageUrls: json['imageUrls'] as List<String>,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'title': title,
      'imageUrls': imageUrls,
    };
  }
}

여기까진 문제가 없었는데, firestore에서 데이터를 불러와 List<Post>로 가공하는 부분에서 아래와 같이 에러가 발생하고 있습니다.

List<Post> posts = snapshot.data!.docs.map((el) => el.data()).toList();

// type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast

 

다음처럼 fromJson 함수를 수정해보려 했는데 해결되지 않아 질문합니다 ㅠㅠ 해결 방법이 있을까요??

import 'dart:convert';

// ...
class Post {

  // ...

  factory Post.fromJson(Map<String, dynamic> jsonData) {

    final imageUrls = json.decode(jsonData['imageUrls']).cast<String>().toList();

    return Post(
      id: jsonData['id'] as String,
      userId: jsonData['userId'] as String,
      title: jsonData['title'] as String,
      imageUrls: imageUrls,
    );
  }

(위와 같이 수정하면 type 'List<dynamic>' is not a subtype of type 'String' 이런 에러 메세지가 뜹니다.

답변 1

답변을 작성해보세요.

0

imageUrls 는 firestore 쪽에 Array 로 저장한 것이지요?

그렇다면 as 로 캐스팅 대신에 List.from 생성자를 사용해 보시겠어요? (확인 못 했음)

만약 안 된다면 디버그 모드에서 json['imageUrls'] 내용이 어떤지 볼 필요가 있을 것 같습니다.

imageUrls: List<String>.from(json['imageUrls'])