Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix type 'int' is not a subtype of type 'String'

In my flutter project I am trying to get the following json API:

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

I have created the following 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,
      };
}

Whenever I try to get the API I run into this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I am note sure how to fix it I have tried following this answer type 'String' is not a subtype of type 'int' but it did not work. My question why I am getting this error although I have set the int

>Solution :

The problem is here:

int.parse(json["id"])

int.parse takes a string but what you are giving it is type int.

Replace that with:

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

You will also need to change user and workout.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading