Преобразование данных JSON в представление списка приводит к ошибке значения типа «Список» не может быть присвоено переменной типа » Карта»

#flutter #dart

Вопрос:

Фон

У меня есть следующие данные JSON, которые удаленно извлекаются с помощью асинхронного запроса, из которых я пытаюсь создать представление списка в Flutter.

 [
  {
    "loggedin": "0"
  }, 
  {
    "id": "1",
    "title": "Title 1",
    "excerpt": "",
    "thumb": "Image 1.jpg",
    "threadid": "1",
    "fid": "1",
    "commentcount": "1",
    "postdate": 1
}, {
    "id": "2",
    "title": "Title 2",
    "excerpt": "",
    "thumb": "Image 2.jpg",
    "threadid": "2",
    "fid": "2",
    "commentcount": "2",
    "postdate": 2
}, {
    "id": "3",
    "title": "Title 3",
    "excerpt": "",
    "thumb": "Image3.jpg",
    "threadid": "3",
    "fid": "3",
    "commentcount": "3",
    "postdate": 3
}
]
 

Что я сделал до сих пор

Используя этот сайт: https://app.quicktype.io Я создал следующую модель:

 List<News> newsFromJson(String str) => List<News>.from(json.decode(str).map((x) => News.fromJson(x)));

String newsToJson(List<News> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class News {
  News({
    required this.loggedin,
    required this.id,
    required this.title,
    required this.excerpt,
    required this.thumb,
    required this.threadid,
    required this.fid,
    required this.commentcount,
    required this.postdate,
  });

  String loggedin;
  String id;
  String title;
  String excerpt;
  String thumb;
  String threadid;
  String fid;
  String commentcount;
  int postdate;

  factory News.fromJson(Map<String, dynamic> json) => News(
    loggedin: json["loggedin"] == null ? null : json["loggedin"],
    id: json["id"] == null ? null : json["id"],
    title: json["title"] == null ? null : json["title"],
    excerpt: json["excerpt"] == null ? null : json["excerpt"],
    thumb: json["thumb"] == null ? null : json["thumb"],
    threadid: json["threadid"] == null ? null : json["threadid"],
    fid: json["fid"] == null ? null : json["fid"],
    commentcount: json["commentcount"] == null ? null : json["commentcount"],
    postdate: json["postdate"] == null ? null : json["postdate"],
  );

  Map<String, dynamic> toJson() => {
    "loggedin": loggedin == null ? null : loggedin,
    "id": id == null ? null : id,
    "title": title == null ? null : title,
    "excerpt": excerpt == null ? null : excerpt,
    "thumb": thumb == null ? null : thumb,
    "threadid": threadid == null ? null : threadid,
    "fid": fid == null ? null : fid,
    "commentcount": commentcount == null ? null : commentcount,
    "postdate": postdate == null ? null : postdate,
  };
}
 

Мой Вопрос

Когда я пытаюсь использовать эти данные, я получаю следующую ошибку:

 Error: A value of type 'List<News>' can't be assigned to a variable of type 'Map<String, dynamic>'.
 

То, что я делаю в отдельном классе, заключается в следующем:

 Future<void> get fetchData async {

    var daUrl = 'https://mywebsitethatservesthejson.com';

    final response = await get(Uri.parse(daUrl));

    if (response.statusCode == 200)
    {
      try
      {



        final decoded = json.decode(response.body) as dynamic;

        decoded.forEach((data) {
          //data is a Map
          if(data.containsKey("loggedin")) {
            _isLoggedIn = int.parse(data["loggedin"]);
          }

        });



        _map = newsFromJson(response.body);
        _error = false;
      }
      catch(e)
      {
        _error = true;
        _errorMessage = e.toString();
        _map = {};
        _isLoggedIn = 0;
      }
    }
    else
    {
      _error = true;
      _errorMessage = 'Error: It could be your internet connection';
      _map = {};
      _isLoggedIn = 0;
    }

    notifyListeners();  // if good or bad we will notify the listeners either way

  }
 

Проблема возникает из-за линии

 _map = newsFromJson(response.body);
 

Комментарии:

1. что такое тип _map ?

Ответ №1:

Вы объявили свою _map переменную как Map или Map<String,dynamic> . Вот почему вы столкнулись с этой проблемой

Ошибка: Значение типа «Список» не может быть присвоено переменной типа » Карта<Строка, динамическая>».

Поскольку возвращаемый тип newsFromJson(response.body) метода является List<News> и _map объявляется как Map .

Комментарии:

1. спасибо, кажется, в этом проблема-Вы знаете, чем я должен объявить _map? Я не знаю, как объявить пустой список<Новости>, чтобы принять мои данные?

2. вы можете написать List<News> _list = []