简体   繁体   中英

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'],
                    ),
                ),
            );
        }
    ),
),

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()));
                  }),
        ));
  }
}

You can remove items except for Apple or Microsoft:

data.removeWhere((item) {
    item['category'] != 'Apple' || item['category'] != 'Microsoft'
});

See also List Dartdoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM