Retrieving JSON data in Flutter based on category

I am in the process of creating an e-commerce application. I am using a ListView.builder to show the data but I'm struggling with fetching products based on the selected category.

Below is the model for the list of categories:

    class Category {
  final int id;
  String name;
  String image;
  String slug;
  

  Category({this.id, this.name, this.image, this.slug});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['id'],
      name: json['name'],
      image: json['image'].toString(),
      slug: json['slug']
    );
  }
}

class Produit {
  
  String productName;
  String productImage;
  int productPrice;
  String description;
  int rating;
  int numberOfRating;
  int category;

  Produit({
    this.productName,
    this.productImage,
    this.productPrice,
    this.description,
    this.rating,
    this.numberOfRating,
    this.category
  });

  factory Produit.fromJson(Map<String, dynamic> json) {
    return Produit(
      productName: json['name'],
      productImage: json["image"],
      productPrice: json["price"],
      description: json["description"].toString(),
      rating: json["rating"],
      numberOfRating: json["numberOfRating"],
      category: json["category"]
    );
  }
}

Here is the widget responsible for displaying the list of products by category:

class ProductPage extends StatefulWidget {
  ProductPage({
    Key key,
    this.categoryId,
  }) : super(key: key);

  int categoryId;

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

class _ProductPageState extends State<ProductPage> {
  List<Produit> _products = List<Produit>();

  

  Future<List<Produit>> fetchProducts() async {
    var url = apilink + prod_url;
    final response = await http.get(url);
    var products = List<Produit>();

    if (response.statusCode == 200) {
      var productsJson = json.decode(response.body);
      for (var productJson in productsJson) {
        products.add(Produit.fromJson(productJson));
      }
      return products;
    } else {
      throw Exception('Unable to load data.');
    }
  }

  @override
  Widget build(BuildContext context) {
    fetchProducts().then((value) {
      _products.addAll(value);
    });
    return Container(
      child: Scaffold(
          appBar: AppBar(
              title: Text('Products'),
              backgroundColor: Colors.amber,
              brightness: Brightness.light,
              actions: <Widget>[
                IconButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (BuildContext context) =>
                                new SearchWidget()));
                  },
                  icon: Icon(
                    Icons.search,
                    color: Colors.white,
                  ),
                  iconSize: 30,
                ),
                CartIconWithBadge(),
              ]),
          body: Container(
              child: ListView.builder(
            itemCount: _products.length,
            itemBuilder: (BuildContext context, int i) {
              return Container(
                child: (_products[i].category == widget.categoryId),
              );
            },
          ))),
    );
  }
}

I need assistance in displaying data based on the selected category. Your help is greatly appreciated. Thank you!

Answer №1

Thank you for updating your question

There are various approaches to achieving your desired outcome; one solution is provided below.

If you have a list of products in the widget, utilize the List.where method to filter the product list by category and display the filtered results on the widget.

For additional information and sample code, click here.

Note: Avoid direct calls to the API function within the build method; instead, opt for using the FutureBuilder widget. The provided code snippet triggers an API call with each build execution. More details and sample code available on flutter docs

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uncaught TypeError: path.resolve was expected to be a function in Node.js

As a newbie in Node.js, I am currently following a tutorial. Although I have written the syntax correctly, I keep encountering a TypeError on path.revole(). I have also implemented the use of async/await. My intention was to send a POST request to the se ...

Using Vuex to fetch information from Laravel

As a newcomer to the world of vue/vuex, I find myself immersed in a laravel project that utilizes these technologies for its front end. Needless to say, I am struggling to grasp the intricacies of it all. My current challenge involves retrieving the folde ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

The rows sent to HTML/Bootstrap from Java through JSON do not neatly wrap across rows evenly

I am having trouble getting images to wrap evenly on an HTML/Bootstrap page that are retrieved by Java and passed through JSON. Despite my expectations, there is a third row created with only one image and a fifth row with 3 extra images. Additionally, whe ...

Incorporating MongoDB into a Node/Express application file

Currently, I am delving into the realm of Mongo db with a specific goal in mind - inserting two variables into mongo. To achieve this, I have outlined the following steps within the same file: 1.- Defining the two variables 2.- Creating a function that ...

Error occurred while retrieving JSON data due to utilizing null check operator on a null value

I'm having trouble understanding this code. builder: (context, snapshot) { if (snapshot.data != null && widget.stored!.b) { return new GridView.count( children: List.generate(snapshot.data!.length, (index) { r ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

"Anticipate the presence of expression" mistake

On my page, users can choose a registration type and input content into the tinymce textarea to associate that content with the selected registration type. However, an error "expression expected" is appearing in the code below? The console indicates that ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code: new Vue({ el: 'body', data:{ role: '', company: '', list:[], ...

Unveiling the information retrieved from an AJAX request during page load

I've been working on a unique concept for my website. Instead of displaying data from a JSON file upon load, I want it to render only when a specific click event occurs. Initially, I tried using callbacks but soon realized the flaws in that approach. ...

Encountering Vue Router Error while integrating Laravel 9 with Vite and Vue CLI 3

I am struggling to fix it, please assist me. I can't seem to pinpoint the issue and need some guidance. Error Image Links: https://i.stack.imgur.com/VhVXL.png https://i.stack.imgur.com/IENFm.png ...

Utilizing XML over JSON in Grape integration with Rails 3 on Heroku platform

While using Grape (https://github.com/intridea/grape) with Rails 3, I encountered an unusual issue. I have set json as the default output format in my API class and I am utilizing the as_json method to display the results. Here's a snippet from my /l ...

What is the best way to handle parsing a JSON object in a single response?

My challenge lies in parsing/converting a GET response to a POJO. Below, I have the User class and the Controller class. In the getUsers() method, I successfully parse the request using ParameterizedTypeReference with the wrapper class. However, I face di ...

The act of substituting elements in Python

I need a way to replace current ID's, which are a combination of numbers and letters, with unique ID's that consist only of numbers. Current ID's: "Id": "a4555752s" "SummaryId": "a4555752s" ...

The REST POST controller is notifying that it encountered an error while attempting to read a JSON file. Specifically, the error message states:

I'm currently attempting to conduct an integration test on a REST controller's POST handler. However, I am facing some difficulties in doing so. During the test, I encountered the HttpMessageNotReadableException exception with the message: "Coul ...

Accessing the Key Name of a JSON Array in Android Using Dynamic Methods

I have a unique json url, which upon opening displays the following data { "Response": "Successful", "All_Items": [{ "Category": "1", "TotalCount": "5", "ExpiringToday": 2 }], "TopOne": [{ "id": "10", "ThumbnailPath": "http://exampleo ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

What is the best way to include all validation attributes from the individual properties when serializing a model?

Situation: I am working on a jsonP service with mvc controller methods that define formfields along with validation rules. The issue I'm facing is figuring out how to serialize the validation attributes. I want the validation attributes to be formatt ...

Getting the error while extracting JSON data using Await.result() with an infinite Duration

Recently, while working with the Scala-Play framework, I encountered an error when trying to fetch data from external websites. The line of code in question is Await.result(xxx, Duration.Inf).json, which resulted in a JsonParseException: Unexpected charact ...