why i got this error Error: Expected a value of type 'List<dynamic>', but got one of type '_JsonMap'

Viewed 85

hi i am making food app that shows recipes form spoonacular api so i made a home screen that get the data and show it in a list view i tried thus 'https://api.spoonacular.com/food/products/search?query=pizza&apiKey=8fe91444f092411fa6011b71fd6e582d'

but when i run the app it says Error: Expected a value of type 'List', but got one of type '_JsonMap' and doesn't show any data

the home screen class

    import 'package:flutter/material.dart';
import 'package:flutter_application_1/recipes.dart';
import 'dart:convert' as cnv;
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreen createState() => _HomeScreen();
}

class _HomeScreen extends State<HomeScreen> {
  List<recipes>? modell;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Food recipe api'),
      ),
      body: modell == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child: ExpansionTile(
                    title: Text(modell![index].type.toString()),
                    children: [
                      Text('modell![index].uri.toString()'),
                      Container(
                        child:
                            Image.network('https://picsum.photos/250?image=9'),
                      )
                    ],
                  ),
                );
              },
              itemCount: modell!.length),
    );
  }

  Future<void> getData() async {
    http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/food/products/search?query=pizza&apiKey=8fe91444f092411fa6011b71fd6e582d'));
    print(res.body);
    List<dynamic> body = cnv.jsonDecode(res.body);
    modell = body.map((dynamic item) => recipes.fromJson(item)).toList();
    setState(() {});
   }
}

the recipes class i used json to dart website to make this class

    class recipes {
  String ? type;
  List<Products> ? products;
  int ? offset;
  int ? number;
  int ? totalProducts;
  int ? processingTimeMs;
  int ? expires;
  bool ? isStale;

  recipes(
      {this.type,
      this.products,
      this.offset,
      this.number,
      this.totalProducts,
      this.processingTimeMs,
      this.expires,
      this.isStale});

  recipes.fromJson(Map<String, dynamic> json) {
    type = json['type'];
    if (json['products'] != null) {
      products = <Products>[];
      json['products'].forEach((v) {
        products!.add(new Products.fromJson(v));
      });
    }
    offset = json['offset'];
    number = json['number'];
    totalProducts = json['totalProducts'];
    processingTimeMs = json['processingTimeMs'];
    expires = json['expires'];
    isStale = json['isStale'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['type'] = this.type;
    if (this.products != null) {
      data['products'] = this.products!.map((v) => v.toJson()).toList();
    }
    data['offset'] = this.offset;
    data['number'] = this.number;
    data['totalProducts'] = this.totalProducts;
    data['processingTimeMs'] = this.processingTimeMs;
    data['expires'] = this.expires;
    data['isStale'] = this.isStale;
    return data;
  }
}

class Products {
  int ? id;
  String ? title;
  String ? image;
  String ? imageType;

  Products({this.id, this.title, this.image, this.imageType});

  Products.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
    image = json['image'];
    imageType = json['imageType'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['image'] = this.image;
    data['imageType'] = this.imageType;
    return data;
  }

}

if you want any further info please comment below thank you!

2 Answers

This is most likely causing your error:

List<dynamic> body = cnv.jsonDecode(res.body);

You need to access the list inside your decoded body, which is at key : "products", to do so, try:

List<dynamic> body = cnv.jsonDecode(res.body)["products"];
Future<void> getData() async {
    http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/food/products/search?query=pizza&apiKey=8fe91444f092411fa6011b71fd6e582d'));
    var body = jsonDecode(res.body);
    Iterable list = body['products'];
    modell = list.map((e) => recipes.fromJson(e)).toList();
   }

Try use iterable if your json is nested.

Related