I got an error when trying to get data from the API error type 'null' is not a subtype of type 'string'

sharon

hello permission to ask I'm trying to get the API to then display and the response is 200 ok. but when I try to display it on the screen the following error occurs

this is a function to get data from API

Future<Datum> getPaketKuliah() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/perwalian/get_paket',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );

    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      return Datum.fromJson(jsonDecode(response.body));
    } else {
      throw Exception();
    }
  }

and I want to display it on the page using FutureBuilder

Container(
              child: FutureBuilder<Datum>(
                future: AuthProvider().getPaketKuliah(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text(snapshot.data!.kelas);
                  } else if (snapshot.hasError) {
                    return Text('${snapshot.error}');
                  }

                  // By default, show a loading spinner.
                  return const CircularProgressIndicator();
                },
              ),
            ),

and lastly this is the model class I want to take to display on the page

// To parse this JSON data, do
//
//     final getPaket = getPaketFromJson(jsonString);

import 'dart:convert';

GetPaket getPaketFromJson(String str) => GetPaket.fromJson(json.decode(str));

String getPaketToJson(GetPaket data) => json.encode(data.toJson());
class GetPaket {
  GetPaket({
    required this.status,
    required this.code,
    required this.data,
  });

  String status;
  String code;
  Map<String, Datum> data;

  factory GetPaket.fromJson(Map<String, dynamic> json) => GetPaket(
        status: json["status"],
        code: json["code"],
        data: Map.from(json["data"])
            .map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "code": code,
        "data": Map.from(data)
            .map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.idDosen,
    this.idMk,
    required this.nidn,
    this.dosen,
    this.idKelasKuliah,
    this.kelasKuliah,
    this.prodi,
    this.kelas,
    this.semester,
    this.kelompokKelas,
    required this.kode,
    this.sks,
    this.jumlahKelas,
    this.matakuliah,
    this.smt,
    this.bobotSks,
    this.rencanaPertemuan,
    this.jenisEvaluasi,
    required this.createdAt,
    required this.updatedAt,
    this.createdBy,
    this.updatedBy,
  });

  String? id;
  String? idDosen;
  String? idMk;
  dynamic nidn;
  String? dosen;
  String? idKelasKuliah;
  String? kelasKuliah;
  String? prodi;
  String? kelas;
  String? semester;
  String? kelompokKelas;
  dynamic kode;
  int? sks;
  int? jumlahKelas;
  String? matakuliah;
  String? smt;
  int? bobotSks;
  int? rencanaPertemuan;
  String? jenisEvaluasi;
  DateTime createdAt;
  DateTime updatedAt;
  String? createdBy;
  String? updatedBy;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        idDosen: json["id_dosen"],
        idMk: json["id_mk"],
        nidn: json["nidn"],
        dosen: json["dosen"],
        idKelasKuliah: json["id_kelas_kuliah"],
        kelasKuliah: json["kelas_kuliah"],
        prodi: json["prodi"],
        kelas: json["kelas"],
        semester: json["semester"],
        kelompokKelas: json["kelompok_kelas"],
        kode: json["kode"],
        sks: json["sks"],
        jumlahKelas: json["jumlah_kelas"],
        matakuliah: json["matakuliah"],
        smt: json["smt"],
        bobotSks: json["bobot_sks"],
        rencanaPertemuan: json["rencana_pertemuan"],
        jenisEvaluasi: json["jenis_evaluasi"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
        createdBy: json["created_by"],
        updatedBy: json["updated_by"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "id_dosen": idDosen,
        "id_mk": idMk,
        "nidn": nidn,
        "dosen": dosen,
        "id_kelas_kuliah": idKelasKuliah,
        "kelas_kuliah": kelasKuliah,
        "prodi": prodi,
        "kelas": kelas,
        "semester": semester,
        "kelompok_kelas": kelompokKelas,
        "kode": kode,
        "sks": sks,
        "jumlah_kelas": jumlahKelas,
        "matakuliah": matakuliah,
        "smt": smt,
        "bobot_sks": bobotSks,
        "rencana_pertemuan": rencanaPertemuan,
        "jenis_evaluasi": jenisEvaluasi,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
        "created_by": createdBy,
        "updated_by": updatedBy,
      };
}

and this is the json response

enter image description here

Soliev

I highly recommend using library like json_serilizable to generate factory fromJson

factory Paket.romJson(Map<String, dynamic> json) => Paket(
      status: json['status'] as String,
      code: json['code'] as String,
      data: (json['data'] as Map<String, dynamic>).map(
        (k, e) => MapEntry(k, Datum.fromJson(e as Map<String, dynamic>)),
      ),
    );

As provided api response corresponds to GetPaket class not Datum class you need to change getPaketKuliah method to

Future<Datum> getPaketKuliah() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/perwalian/get_paket',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );

    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      // --return Datum.fromJson(jsonDecode(response.body));
           final paket = GetPaket.fromJson(jsonDecode(response.body));
          // -- return Datum.fromJson(paket.data.entries.first.value);
           return paket.data.entries.first.value;
    } else {
      throw Exception();
    }
  }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

I got error when I tried to get data from server

type 'int' is not a subtype of type 'String' error in Dart

Getting 'String is not a subtype of type 'List<dynamic>' error when calling clientViaServiceAccount

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

Fetching Json from api error Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

Flutter error when passing data from one view to another. Error type 'Song' is not a subtype of type 'Song'

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

i got this error "Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast" as below

Flutter : I'm trying to fetch api data into listview , got that error " type 'String' is not a subtype of type 'int' of 'index' "

Flutter Error "not a subtype of type 'String'

Type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast error

When i am trying to fetch api this error : "type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>" shows up

How to solve error "type 'Null' is not a subtype of type 'String' in type cast"

How do i solve the error : type 'Null' is not a subtype of type 'String'

flutter error type 'Null' is not a subtype of type 'String'

type 'Null' is not a subtype of type 'String' in type cast ERROR

_TypeError (type 'Null' is not a subtype of type 'String') - error happening in flutter

type 'Null' is not a subtype of type 'String' this error pops up when trying to access data from map

Error saving data. - (Null' is not a subtype of type '(String, dynamic)

When retrieving api's values I get "_TypeError (type 'Null' is not a subtype of type 'String')"

dart/flutter:: type 'Null' is not a subtype of type 'String' in type cast ERRor, not able to fetch data

Flutter: problem in fetching data: type 'Null' is not a subtype of type 'String' error

type 'Null' is not a subtype of type 'String' when get data

When binding data to kendo-grid got error Type 'T[] | null' is not assignable to type 'any[]' in Angular app

Getting type 'Null' is not a subtype of type 'String' error when using BlocBuilder

Why am I seeing the error 'type 'Null' is not a subtype of type 'int'' in my Flutter http API call?

Flutter error: "The type 'null' is not a subtype of type 'String' in type cast"

Flutter - Type "Null" is not a subtype of type "Widget" error

I am creating a add task app and when I ran the app I get an error that says 'type "Null" is not a subtype of type "String"