Search code examples
jsonflutterdart

Load JSON data with specific category in the ListView in Flutter


I have a JSON list of products of two companies, Apple and Windows. The below is my JSON data structure:

[
  {
    "category": "Apple",
    "name": "Macbook Air"
  },
  {
    "category": "Apple",
    "name": "Macbook Pro"
  },
  {
    "category": "Microsoft",
    "name": "Surface"
  },
  {
    "category": "Apple",
    "name": "iPad"
  },
  {
    "category": "Microsoft",
    "name": "Windows"
  },
  {
    "category": "Apple",
    "name": "Siri"
  },
  {
    "category": "Microsoft",
    "name": "Office"
  }
]

I am trying to create a listview of either Apple or Microsoft category. But in my current listview, it shows all the products from the JSON file:

  List data;

  Future<String> loadJsonData() async{
    var jsonText = await rootBundle.loadString('assets/json/products.json');
    setState(() => data = json.decode(jsonText));
  }

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

The above code loads all the products of both companies. But how can I load only the products of Apple or Microsoft?

This is my ListView

Container(
    child: data == null ? Container() : ListView.builder(
        itemCount: data.length,
        itemBuilder: (BuildContext context, int index) {
            return Container(
                child: ListTile(
                    title: Text(
                        data[index]['name'],
                    ),
                ),
            );
        }
    ),
),

Solution

  • You can do something like this:

     @override
      Widget build(BuildContext context) {
        return Scaffold(
            backgroundColor: Color(0xfff5f5f5),
            appBar: AppBar(
              title: Text('Demo'),
            ),
            body: Container(
              child: data == null
                  ? Container()
                  : ListView.builder(
                      itemCount: data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Container(
                            child: ((data[index]['category'] == "Apple")
                                ? ListTile(title: Text(data[index]['name']))
                                : Container()));
                      }),
            ));
      }
    }