简体   繁体   English

Flutter中ListView加载指定类别的JSON数据

[英]Load JSON data with specific category in the ListView in Flutter

I have a JSON list of products of two companies, Apple and Windows .我有两家公司的 JSON 产品列表, AppleWindows The below is my JSON data structure:下面是我的 JSON 数据结构:

[
  {
    "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.我正在尝试创建AppleMicrosoft类别的列表视图。 But in my current listview, it shows all the products from the JSON file:但在我当前的列表视图中,它显示了 JSON 文件中的所有产品:

  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 ?但是我怎样才能只加载AppleMicrosoft的产品呢?

This is my ListView这是我的列表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:您可以删除 Apple 或 Microsoft 以外的项目:

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

See also List Dartdoc另见列表 Dartdoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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