Home > OS >  type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => Map
type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => Map

Time:11-13

So I tried to consume the API and I keep getting this error type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

This is my category model

import 'dart:convert';    

List<Category> categoryFromJson(String str) =>
        List<Category>.from(json.decode(str).map((x) => Category.fromJson(x))); // I get the error here
    
    String categoryToJson(List<Category> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class Category {
      Category({
        required this.id,
        required this.name,
        required this.icon,
      });
    
      int id;
      String name;
      String icon;
    
      factory Category.fromJson(Map<String, dynamic> json) => Category(
            id: json["id"],
            name: json["name"],
            icon: json["icon"],
          );
    
      Map<String, dynamic> toJson() => {
            "id": id,
            "name": name,
            "icon": icon,
          };
    }

This is my category repository. more like services

import 'package:elibrary/services/requests.dart';
import 'package:elibrary/services/endpoints.dart';
import 'package:get/get.dart';

class CategoryRepository extends GetxService {
  ApiClient apiClient = ApiClient();

  Future<Response> getCategories() async {
    return await apiClient.getRequest(ProjectConstants.CATEGORY_URI);
  }
}

This is the category controller

import 'dart:io';

import 'package:elibrary/model/categories.dart';
import 'package:elibrary/services/repository/category_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class CategoryController extends GetxController {
  CategoryRepository categoryRepository = CategoryRepository();

  RxList<Category> categoryList = <Category>[].obs;
  RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    getCategoryList();
  }

  Future<void> getCategoryList() async {
    isLoading(true);
    try {
      Response categoryResponse = await categoryRepository.getCategories();
      if (categoryResponse.statusCode == 200) {
        categoryList.assignAll(
          categoryFromJson(categoryResponse.bodyString ?? ''),
        );
      } else {
        debugPrint(categoryResponse.bodyString ?? '');
        debugPrint(
          categoryResponse.statusText.toString(),
        );
      }
    } on SocketException {
      GetSnackBar(
        message: "No Internet Connectivity",
        duration: Duration(seconds: 5),
      ).show();
    } catch (e) {
      debugPrint(
        e.toString(),
      );
    } finally {
      isLoading(false);
    }
  }

  SnackbarController showErrorMessage(
      Response<dynamic> categoryResponse, String message) {
    return Get.snackbar(
      "Error Occurred",
      categoryResponse.statusText.toString(),
      snackPosition: SnackPosition.BOTTOM,
      colorText: Colors.white,
      backgroundColor: Colors.red,
    );
  }
}

I tried to use for in loop by doing it this way

by changing this

List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)));

to this

List<Category> categoryFromJson(String str) => [
      for (Map<String, dynamic> x in json.decode(str)) Category.fromJson(x),
    ];

But it give me this error

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'

I have read this Unhandled Exception

I have read this too Exception has occurred

I have again this also flutter _TypeError

CodePudding user response:

try changing the below line of code

List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)));

to (add toList() to the map closure)

List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)).toList());

CodePudding user response:

Try this:

List<Category> categoryFromJson(String str) => (json.decode(str)["data"] as List<Map<String, dynamic>>).map((x) => Category.fromJson(x)).toList();

or if you want for loop format:

List<Category> categoryFromJson(String str) => [
      for (Map<String, dynamic> x in json.decode(str)["data"]) Category.fromJson(x),
    ];
  • Related