flutter 如何修复类型“int”不是类型“String”的子类型

f0brbegy  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(190)

在我的flutter项目中,我尝试获取以下json API:

[
    {
        "id": 12,
        "active": false,
        "name": "Flat",
        "user": 10,
        "workout": 4
    },
    {
        "id": 15,
        "active": false,
        "name": "Inclined",
        "user": 10,
        "workout": 4
    }
]

我已经创建了以下exercises_model.dart:

// To parse required this JSON data, do
//
//     final exercisesModel = exercisesModelFromJson(jsonString);
 
import 'dart:convert';
 
List<Exercises_Model> ExercisesModelFromJson(dynamic decodedResponse) =>
    List<Exercises_Model>.from(
        decodedResponse.map((x) => Exercises_Model.fromJson(x)));
 
String exercisesModelToJson(List<Exercises_Model> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
 
class Exercises_Model {
  Exercises_Model({
    required this.id,
    required this.active,
    required this.name,
    required this.user,
    required this.workout,
  });
 
  int id;
  bool active;
  String name;
  int user;
  int workout;
 
  factory Exercises_Model.fromJson(Map<String, dynamic> json) =>
      Exercises_Model(
        // id: json["id"],
        // active: json["active"],
        // name: json["name"],
        // user: json["user"],
        // workout: json["workout"],
        id: int.parse(json["id"]),
        active: json["active"],
        name: json["name"],
        user: int.parse(json["user"]),
        workout: int.parse(json["workout"]),
      );
 
  Map<String, dynamic> toJson() => {
        "id": id,
        "active": active,
        "name": name,
        "user": user,
        "workout": workout,
      };
}

每当我尝试获取API时,都会遇到以下错误:

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

我注意到如何修复它,我已经尝试按照这个答案type 'String' is not a subtype of type 'int',但它没有工作。我的问题,为什么我得到这个错误,虽然我已经设置了int

exdqitrt

exdqitrt1#

问题就在这里:

int.parse(json["id"])

int.parse接受一个字符串,但你给它的是int类型。
将其替换为:

int.parse(json["id"].toString())

您还需要更改userworkout

相关问题