user18031298
user18031298

Reputation:

Exception in json.decode : Closure: () => String from Function 'toString'

I am getting some data from API in flutter. I am trying to decode the data using json.decode() but this decode function gives me the following error:

Closure: () => String from Function 'toString'

Here's my code:

Future<Product> createOrder() async {
    var client = new http.Client();
    var productModel = null;

    try {
      var response = await client
          .get(Uri.https('butterbasket.onrender.com', Strings.createOrderUrl));
      if (response.statusCode == 200) {
        var body = response.body;
        print("Body: $body");
        var jsonMap = json.decode(body);
        var productModel = Product.fromJson(jsonMap);
      }
    } catch (e) {
      print("Exception: ${e.toString}");
    }
    return productModel;
  }

Here is the Error Debug Console: Debug Console

Upvotes: 2

Views: 1145

Answers (2)

You are running into issues because the data you are loading in is an array, but the model is an object. You'll need to do something like the following:

final List jsonProducts = json.decode(body)
final List<Product> products = 
     jsonProducts.map((jsonProduct) => Product.fromJson(jsonProduct)).toList();

and then if you only need the first item you can do:

final Product product = products[0]

But don't forget to check if the array is big enough.

Upvotes: 2

Your Future function must return an optional Product?, otherwise your future will never find a result as you are declaring it inside the function.

Instead of:

Future<Product> createOrder() async {}

Use:

Future<Product?> createOrder() async {}

Finally your async snapshot and FutureBuilder type should be of type <Product?>.

Upvotes: 1

Related Questions