1

I'm making a mobile app for shopping

I want to replace the static data with data from json online to and put this data in a structure to show it using Gridview and use it somewhere else so this is the structure:

    class Product {

  String _urlToImage;
  String _about;
  String _title;
  double _price;
  double _weight;
  int _id;


  Product(this._urlToImage, this._title, this._price, this._weight, this._id){
    _about = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
  }

  double get weight => _weight;

  double get price => _price;

  String get title => _title;

  String get urlToImage => _urlToImage;

  int get id => _id;

  String get about => _about;


}
```

and this is the local data inside the struct

  class ProductsRepository{

List<Product>  fetchAllProducts() {

return [
  new Product("assets/images/spelt_noodles.png", "Biona Organic Spelt Noodles", 2.99, 250, 0),
  new Product("assets/images/spelt_italian.png", "Biona Organic Spelt Fusili Brown", 2.35, 500, 1),
  new Product("assets/images/spelt_spaghetti.png", "Biona Organic Whole Spelt Spaghetti", 2.35, 500, 2),
  new Product("assets/images/spelt_tagliatelle.png", "Biona Organic Spelt Spinach Artisan Tagliatelle", 1.99, 250, 3),
  new Product("assets/images/spelt_penne.png", "Biona Organic Whole Spelt Penne", 2.35, 500, 4),
  new Product("assets/images/spelt_tagliatelle.png", "Biona Organic Spelt Spinach Artisan Tagliatelle", 1.99, 250, 5),
  new Product("assets/images/spelt_fusilli.png", "Biona Organic Spelt Fusilli Tricolore", 1.99, 250, 6),
];}

I tried

  _fetchData() async {

    final response =
    await http.get("https://jsonplaceholder.typicode.com/photos");
        if (response.statusCode == 200) {
          list = json.decode(utf8.decode(response.bodyBytes)) as List;

    } else {
    throw Exception('Failed to load photos');
    }
  }

just like this concept but the json data should be in the Product() struct

List data;

Future<String> getData() async {
  var response = await http.get(
      Uri.encodeFull("https://aflam4app.de/JSON/" + widget.thisJson +".json"),
      headers: {
        'Content-Type': 'application/json',
        "Accept": "application/json"
      }
  );

  this.setState(() {
    data = json.decode(utf8.decode(response.bodyBytes));
  });
  return "Success!";
}


@override
void initState() {
  super.initState();
  this.getData();
}

@override
Widget build(BuildContext context) {
  return GridView.builder(
      itemCount: data == null ? 0 : data.length,
      gridDelegate:
      new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        return Padding(
          padding: const EdgeInsets.all(4.0),
          child: Single_prod(
            prod_name: data[index]['name'],
            prod_pricture: data[index]['picture'],
            prod_link: data[index]['link'],
            prod_description: data[index]['description'],
            prod_type: data[index]['type'],
          ),
        );
      });
}
}

class Single_prod extends StatelessWidget {
final prod_name;
final prod_pricture;
final prod_link;
final prod_description;
final prod_type;

Single_prod({
  this.prod_name,
  this.prod_pricture,
  this.prod_link,
  this.prod_description,
  this.prod_type,
});

here is my json file:

[
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 1,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 2,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 3,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },


]
Wail Hayaly
  • 1,057
  • 1
  • 15
  • 31
  • 1
    So what is the issue here, would you like to know how to implement a gridview or convert your json into a product object? – F-1 Jul 09 '19 at 13:21

1 Answers1

2

This is how you can parse the data

    List<Product> list = new List<Product>();
    var map= json.decode(response.body);

    for(var item in map){
      Product product = new Product.fromJson(item); //making an assumption how your json looks
      list.add(product); //user a Futurebuilder to create your GridView
    }

This how you can define your model class

    Product fromJson(Map<String, dynamic> json){
      Product product = new Product(
        _urlToImage = json['urlToImage'] as String;
        _about = json['about'] as String;
        _title = json['title'] as String;
        _price = json['price'] as double;
        _weight = json['weight'] as double;
        _id = json['id'] as int;
      );
      return product;
    }

    ...

Here Gridview example

F-1
  • 2,887
  • 20
  • 28
  • What didn't work? What was the error? As I mentioned in my answer without seeing the Json I have to guess. Your question and response is very vague. – F-1 Jul 09 '19 at 14:27
  • It's all about making these Product(...) data comes from my json instead of the data already there, so every time I add a new product from the API it would show in the app – Wail Hayaly Jul 09 '19 at 14:33
  • Can you add a snippet of your json to your original post so we can see how it is structured. Also, if you can paste the error message or take a screen shot it using imgur post it in a reply that would be useful as well. – F-1 Jul 09 '19 at 14:40
  • I did hopefully, you can understand me now – Wail Hayaly Jul 09 '19 at 14:51
  • Thank you. When you tested the code did you change the my map code to match your json attibutes? Because it is case sensitive. I originally had starting with caps but I've edited it now to match your json, so you shouldn't have an issue creating the product now. Use debugger breakpoints to see how it is working. – F-1 Jul 09 '19 at 15:26