【问题标题】:cannot resolve type 'String' is not a subtype of type 'int' of 'index'无法解析类型“字符串”不是“索引”的“int”类型的子类型
【发布时间】:2020-02-27 10:34:41
【问题描述】:

我最近开始遇到问题。我需要将我的 json response 解析为 list 到我的模型对象类,但我不断收到此错误:

type 'String' is not a subtype of type 'int' of 'index'

在线尝试了几种解决方案,但对我不起作用。我是我的模型类中的变量声明是问题,所以我将它们更改为动态但对我仍然不起作用。

标题

型号

class MenteeIndex {
  dynamic id;
  dynamic mentor_id;
  dynamic mentee_id;
  dynamic status;
  dynamic session_count;
  dynamic current_job;
  dynamic email;
  dynamic phone_call;
  dynamic video_call;
  dynamic face_to_face;
  dynamic created_at;
  dynamic updated_at;

  MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
      this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);

  Map<String, dynamic> toJson() => {
    'id': id,
    'mentor_id': mentor_id,
    'mentee_id': mentee_id,
    'status': status,
    'session_count': session_count,
    'current_job': current_job,
    'email':email,
    'phone_call': phone_call,
    'video_call': video_call,
    'face_to_face': face_to_face,
    'created_at': created_at,
    'updated_at': updated_at,
  };

  MenteeIndex.fromJson(Map<String, dynamic> json):
        id = json['id'],
        mentor_id = json['mentor_id'],
        mentee_id = json['mentee_id'],
        status = json['status'],
        session_count = json['session_count'],
        current_job = json['current_job'],
        email = json['email'],
        phone_call = json['phone_call'],
        video_call = json['video_call'],
        face_to_face = json['face_to_face'],
        created_at = json['created_at'],
        updated_at = json['updated_at'];
}

主要

 Future fetchIndex() async {
        SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
        var uri = NetworkUtils.host + AuthUtils.endPointIndex;
        try {
          final response = await http.get(
            uri,
            headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
          );
          var encodeFirst = json.encode(response.body);
          final responseJson = json.decode(encodeFirst);
    //here is where the error is
          for (var u in responseJson["data"]) {
            MenteeIndex user = MenteeIndex(
                u["id"],
                u["mentor_id"],
                u["mentee_id"],
                u["status"],
                u["session_count"],
                u["current_job"],
                u["email"],
                u["phone_call"],
                u["video_call"],
                u["face_to_face"],
                u["created_at"],
                u["updated_at"]);

            menteeIndexes.add(user);
            setState((){
               mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
              indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
              status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
            });
          }
          return responseJson;
        } catch (exception) {
          print(exception);
        }
          }

响应/错误

 {"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'

【问题讨论】:

  • 你在哪一行得到了错误?
  • 你好,本。请按照@Darish 的建议提供发生错误的行,尽管我怀疑当您map for`mentorIdList`indexIds 时会发生错误。如果它们中的任何一个是 List&lt;int&gt; 并且您从服务器获得的响应是​​字符串,则您需要使用 `int.prase(value) 解析它们。
  • 我在将解码后的对象保存到被指导对象中时遇到错误。
  • @Darishi 刚刚发布了我的 json 响应和错误。
  • 是的,mentor_id 确实是 String 而不是 int,所以如果 mentorIdListList&lt;int&gt; 你将不得不 parse 映射到 int 时的值,如下所示: mentorIdList = menteeIndexes.map((MenteeIndex) =&gt; int.parse(MenteeIndex.mentor_id));

标签: json flutter dart


【解决方案1】:

将响应正文解码为Map

final responseJson = json.decode(response.body);

Map 列表转换为MenteeIndex 列表

  final menteeIndexes = responseJson["data"].map(
        (json) => MenteeIndex.fromJson(json)
      ).toList();

【讨论】:

    【解决方案2】:

    查看这个模型类

    // To parse this JSON data, do
    //
    //     final yourModel = yourModelFromJson(jsonString);
    
    import 'dart:convert';
    
    YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));
    
    String yourModelToJson(YourModel data) => json.encode(data.toJson());
    
    class YourModel {
        int currentPage;
        List<Datum> data;
    
        YourModel({
            this.currentPage,
            this.data,
        });
    
        factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
            currentPage: json["current_page"],
            data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "current_page": currentPage,
            "data": List<dynamic>.from(data.map((x) => x.toJson())),
        };
    }
    
    class Datum {
        int id;
        String mentorId;
        String menteeId;
        dynamic status;
        int sessionCount;
        dynamic currentJob;
        dynamic email;
        dynamic phoneCall;
        dynamic videoCall;
        dynamic faceToFace;
        DateTime createdAt;
        DateTime updatedAt;
    
        Datum({
            this.id,
            this.mentorId,
            this.menteeId,
            this.status,
            this.sessionCount,
            this.currentJob,
            this.email,
            this.phoneCall,
            this.videoCall,
            this.faceToFace,
            this.createdAt,
            this.updatedAt,
        });
    
        factory Datum.fromJson(Map<String, dynamic> json) => Datum(
            id: json["id"],
            mentorId: json["mentor_id"],
            menteeId: json["mentee_id"],
            status: json["status"],
            sessionCount: json["session_count"],
            currentJob: json["current_job"],
            email: json["email"],
            phoneCall: json["phone_call"],
            videoCall: json["video_call"],
            faceToFace: json["face_to_face"],
            createdAt: DateTime.parse(json["created_at"]),
            updatedAt: DateTime.parse(json["updated_at"]),
        );
    
        Map<String, dynamic> toJson() => {
            "id": id,
            "mentor_id": mentorId,
            "mentee_id": menteeId,
            "status": status,
            "session_count": sessionCount,
            "current_job": currentJob,
            "email": email,
            "phone_call": phoneCall,
            "video_call": videoCall,
            "face_to_face": faceToFace,
            "created_at": createdAt.toIso8601String(),
            "updated_at": updatedAt.toIso8601String(),
        };
    }
    
    

    只需将您的 response.body 插入此方法即可:

     final yourModel = yourModelFromJson(response.body);
    

    您可以使用以下调用获取数据列表:

    List<Datum> dataList = List();
    
    dataList = yourModel.data;
    
    

    这里是数据列表

    你会从中得到你的 Single 对象,然后你可以做任何你想做的事情。

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 1970-01-01
      • 2020-07-02
      • 2021-04-24
      • 1970-01-01
      • 2019-08-12
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多