NoSuchMethodError : The method 'map' was called on null while get API json

Viewed 22

i've had problem with my code while get data from API using flutter framework. they say :

NoSuchMethodError : The method 'map' was called on null.

Receiver: null

Tried calling : map(closure => (dynamic) => Product)

i'm very confused because i'm new on flutter language.. may someone help me?

here my code for Api Response

Future<ApiResponse> getProducts() async {
  ApiResponse apiResponse = ApiResponse();
  try {
    String token = await getToken();
    final response = await http.get(Uri.parse(productURL),
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    });

    switch(response.statusCode){
      case 200:
        apiResponse.data = jsonDecode(response.body)['products'].map((p) => Product.fromJson(p)).toList();
        apiResponse.data as List<dynamic>;
        break;
      case 401:
        apiResponse.error = unauthorized;
        break;
      default:
        apiResponse.error = somethingWentWrong;
        break;
    }
  }
  catch (e){
    apiResponse.error = e.toString();
  }
  return apiResponse;
}

and this my model

class Product {
  int? id;
  String? name;
  String? price;
  String? stock;
  String? type;
  String? description;
  String? image;
  String? likesCount;
  String? commentsCount;
  User? user;
  bool? selfLiked;

  Product({
    this.id,
    this.name,
    this.price,
    this.stock,
    this.type,
    this.description,
    this.image,
    this.likesCount,
    this.commentsCount,
    this.user,
    this.selfLiked,
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'],
      name: json['name'],
      price: json['price'],
      stock: json['stock'],
      type: json['type'],
      description: json['description'],
      image: json['image'],
      likesCount: json['likes_count'],
      commentsCount: json['comments_count'],
      selfLiked: json['likes'].length > 0,
      user: User(
        id: json['user']['id'],
        name: json['user']['name'],
        image: json['user']['image'],
      ),
    );
  }
}
0 Answers
Related