0

I am trying to get the link of an image from a REST service I already built. This is the result of the GET:

{
    "products": {
        "_id": "60abddf1413e7c408c103f6a",
        "product_image": "www.google.com",
        "createdAt": "2021-05-24T17:10:09.738Z",
        "__v": 0
    }
}

And this is my code of a route calling this GET service within flutter:

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final response =
      await http.get(Uri.parse('http://10.0.2.2:3000/product/last'));

  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}

class Product {
  final String product_image;
  final String createdAt;

  Product({
    this.product_image,
    this.createdAt
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      product_image: json['product_image'],
      createdAt: json['createdAt']
    );
  }
}

class Album {
  final Product products;

  Album({
    this.products,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      products: json['products']
    );
  }
}

class PromotionsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final arg = ModalRoute.of(context).settings.arguments;
    Future<Album> futureAlbum = fetchAlbum();

    return Scaffold(
      appBar: AppBar(
        title: Text('Promotions Page'),
      ),
      body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.products.product_image);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
    );
  }
}

but keeps throwing the error, and I don't understand very well why. I think is something related to the parsing section, an object inside another object, but I don't understand what I am doing wrong.

enter image description here

1 Answer 1

1

You're not calling your Product.fromJson constructor in your Album.fromJson constructor. json['products'] is a Map and you're trying to assign it to a Product.

Call Product.fromJson:

factory Album.fromJson(Map<String, dynamic> json) {
  return Album(
    products: Product.fromJson(json['products']),
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

You are awesome, thank you very much. I thought since I defined it in the constructor I should not set it up like that again. Thank you.
@FeberCastellon Please accept the answer if it solved your problem.
Yes, its just that I was waiting a few minutes, couldnt do it before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.