flutter Fetch json data by category

I am currently developing an ecommerce app. I use a ListView.builder to display data but I don’t know how to fetch the products according to the selected category.

Here is the model of 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["prix"],
      description: json["description"].toString(),
      rating: json["rating"],
      numberOfRating: json["numberOfRating"],
      category: json["category"]
    );
  }
}

This is the widget that displays the list of products by category.

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

  int categoryId;

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

class _ProduitPageState extends State<ProduitPage> {
  List<Produit> _produits = List<Produit>();

  

  Future<List<Produit>> fetchProduits() async {
    //var url = 'http://192.168.8.100:8000/api/produits';
    var url = apilink + prod_url;
    final response = await http.get(url);
    var produits = List<Produit>();

    if (response.statusCode == 200) {
      var produitsJson = json.decode(response.body);
      for (var produitJson in produitsJson) {
        produits.add(Produit.fromJson(produitJson));
      }
      return produits;
    } else {
      throw Exception('Impossible de charger les données.');
    }
  }

  @override
  Widget build(BuildContext context) {
    fetchProduits().then((value) {
      _produits.addAll(value);
    });
    return Container(
      child: Scaffold(
          appBar: AppBar(
              title: Text('Restaurant'),
              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: _produits.length,
            itemBuilder: (BuildContext context, int i) {
              return Container(
                child: (_produits[i].category == categoryId),
              );
            },
          ))),
    );
  }
}

Now I want to display data by selected category. Please I really need your help. thanks!!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Thank you for updating your question

While there are many ways you can achieve your desired result, I have mentioned one solution below.

Since you have a list of products available in the widget, you can use the List.where method to filter the product list by category and display the results of that function in your widget

More details and sample code available on

Note: Replace calling the API function in the build method directly and replace it with the FutureBuilder widget. The code sample above will make a call to the API on each build.
More details and sample code available on flutter docs


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x