Search code examples
flutterdartdiocubit

parsing json into flutter List<dynamic> to Map<String, dynamic>


Hello I want to parse Json and I faced this issue what's wrong please help
the error was 'List' is not a subtype of type 'Map<String, dynamic>'
Model

class CategoriesModel {
  CategoriesModel({
    this.id,
    this.title,
    this.price,
    this.description,
    this.image,
  });

  int? id;
  String? title;
  double? price;
  String? description;
  String? image;

  factory CategoriesModel.fromJson(Map<String, dynamic> json) {
    return CategoriesModel(
      id: json["id"],
      title: json["title"],
      price: json["price"].toDouble(),
      description: json["description"],
      image: json["image"],
    );
  }


  Map<String, dynamic> toMap() => {
    "id": id,
    "title": title,
    "price": price,
    "description": description,
    "image": image,
  };
}

in cubit I did this (AppCubit.dart)

CategoriesModel? categoriesModel ;

   getCategories(){
    emit(OnLoadingCategoriesState());
    DioHelper.getData(pathUrl: "products").then((value){
      categoriesModel = CategoriesModel.fromJson(value.data);
      // catList =  (value.data as List)
      //     .map((x) => CategoriesModel.fromJson(x))
      //     .toList();
      // print(catList.length);

      emit(OnSuccessCategoriesState());
    }).catchError((error){
      emit(OnCatchErrorCategoriesState(error.toString()));
      print(error.toString());
    });
  }

in Dio Helper I did general function to use it

  static Future<Response> getData({required pathUrl})async{
   return await dio.get(pathUrl);
  }

and this is small data from json

[
  {
    "id": 1,
    "title": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
    "price": 109.95,
    "description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
    "category": "men's clothing",
    "image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"
  },
  {
    "id": 2,
    "title": "Mens Casual Premium Slim Fit T-Shirts ",
    "price": 22.3,
    "description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
    "category": "men's clothing",
    "image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg"
  },
]

finally this is error that was appeared to me

I/flutter (31455): onChange -- AppCubit, Change { currentState: Instance of 'OnLoadingCategoriesState', nextState: Instance of 'OnCatchErrorCategoriesState' }
I/flutter (31455): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

any help I'll appreciated


Solution

  • CategoriesModel.fromJson is expecting the type Map<String, dynamic> but the json snippet shows that the response is a List.

    Update the .then function to handle the list and create the CategoriesModel from each item in the List, Similar to the code that is commented out in the snippet above.

     DioHelper.getData(pathUrl: "products").then((List values) {
         values.map((e) => CategoriesModel.fromJson(e)).toList();
     }