【问题标题】:_TypeError (type 'List' is not a subtype of type 'Map') flutter_TypeError(类型'List'不是类型'Map'的子类型)颤动
【发布时间】:2020-02-01 18:35:24
【问题描述】:

我在这里做了一个类似的帖子:problem,但我也做了同样的事情,我一直有问题......

我有我的课:

class PollQuestionsDto {
  int id;
  String entitled;
  int difficulty;
  List<Answer> answers;

  PollQuestionsDto({this.id, this.entitled, this.difficulty, this.answers});

  PollQuestionsDto.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    entitled = json['entitled'];
    difficulty = json['difficulty'];
    if (json['answers'] != null) {
      answers = new List<Answer>();
      json['answers'].forEach((v) {
        answers.add(new Answer.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['entitled'] = this.entitled;
    data['difficulty'] = this.difficulty;
    if (this.answers != null) {
      data['answers'] = this.answers.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

询问API方法:

Future<List<PollQuestionsDto>> getPollQuestions() async {
    String url = 'http://10.0.2.2:3000/v1/api/poll/40/question?page=0';
    //String url = 'http://10.0.2.2:3000/v1/api/poll/$idPoll/question?page=0';
    String token = await Candidate().getToken();
    final response = await http.get(url, headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Type': 'application/json; charset=utf-8',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });
    if (response.statusCode == 200) {
      print(jsonDecode(response.body));
      /*List pollsList = jsonDecode(response.body) ;
      List<PollQuestionsDto> polls = [];
      for (var themeMap in pollsList) {
        polls.add(PollQuestionsDto.fromJson(themeMap));
      }
      print(polls);
      print('Get Poll ${response.body}');*/
    } else {
      throw Exception('Failed get poll questions');
    }
  }

当我询问我的 API 时,请求的结果是:

{结果:[{id:2,标题:Le langage utilisé sous Flutter est le dart?,难度:1,答案:[{id:9,标题:Oui,isCorrect:true},{id:10,标题:Non,isCorrect:false}]}],pageCount:3,下一个:http://localhost:3000/v1/api/poll/40/question?page=1,上一个:}

当我想在列表中生成结果时,我有同样的错误:

_TypeError(类型'List'不是类型'Map'的子类型)

为什么?

【问题讨论】:

    标签: mobile flutter dart flutter-layout


    【解决方案1】:

    如果结果是

    {
      "results": [
        {
          "id": 2,
          "entitled": "Le langage utilisé sous Flutter est le dart ?",
          "difficulty": 1,
          "answers": [
            {
              "id": 9,
              "entitled": "Oui",
              "isCorrect": true
            },
            {
              "id": 10,
              "entitled": "Non",
              "isCorrect": false
            }
          ]
        }
      ],
      "pageCount": 3,
      "next": "http://localhost:3000/v1/api/poll/40/question?page=1"
    }
    

    你需要像这样添加['results']

    List pollsList = jsonDecode(jsonstr)['results'];
    

    【讨论】:

      【解决方案2】:

      您需要将json['answers'] 转换为List 喜欢

          if (json['answers'] != null) {
            answers = (json['answers'] as List).map((v) => Answer.fromJson(v)).toList();
          }
      

      除非您有特殊要求,否则最好使用https://pub.dev/packages/json_annotation 而不是手动实现toJsonfromJson

      我能够解析以下字符串

          [
            {
              "id": 1,
              "entitled": "yes",
              "difficulty": 1,
              "answers": [
                {
                  "value":"a"
                }
              ]        
            }
          ]
      
      

      使用

      class PollQuestionsDto {
        int id;
        String entitled;
        int difficulty;
        List<Answer> answers;
      
        PollQuestionsDto({this.id, this.entitled, this.difficulty, this.answers});
      
        PollQuestionsDto.fromJson(Map<String, dynamic> json) {
          id = json['id'];
          entitled = json['entitled'];
          difficulty = json['difficulty'];
          if (json['answers'] != null) {
            answers = new List<Answer>();
            json['answers'].forEach((v) {
              answers.add(new Answer.fromJson(v));
            });
          }
        }
      
        Map<String, dynamic> toJson() {
          final Map<String, dynamic> data = new Map<String, dynamic>();
          data['id'] = this.id;
          data['entitled'] = this.entitled;
          data['difficulty'] = this.difficulty;
          if (this.answers != null) {
            data['answers'] = this.answers.map((v) => v.toJson()).toList();
          }
          return data;
        }
      
        @override String toString() => toJson().toString();
      
        static List<PollQuestionsDto> arrayOfQuestionsFromJson(String json) {
          return (jsonDecode(json) as List).map((e) => PollQuestionsDto.fromJson(e)).toList();
        }
      }
      
      

      这是您所期望的吗(您可能必须更改 json 以获取答案,因为我使用带有一个变量 value 的 Anser 类)??

      【讨论】:

      • 您是否尝试过将json['answers'] 替换为json['answers'] as List 的解决方案?
      • 我这样做了: Map toJson() { final Map data = new Map();数据['id'] = this.id;数据['entitled'] = this.entitled;数据['难度'] = this.difficulty; if (data['answers'] != null) { answers = (data['answers'] as List).map((v) => Answer.fromJson(v)).toList(); } 返回数据; }
      • 我总是遇到同样的错误@Chenna Reddy _TypeError (type '_InternalLinkedHashMap' is not a subtype of type 'List')
      • @MayuriXx 用示例更新了答案,检查arrayOfQuestionsFromJson
      • 我用你的例子编辑了我的帖子,但我总是出错...
      猜你喜欢
      • 2020-01-18
      • 2021-09-12
      • 2021-02-25
      • 2020-06-21
      • 2019-08-18
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多