【问题标题】:Load JSON data with specific category in the ListView in Flutter在 Flutter 的 ListView 中加载特定类别的 JSON 数据
【发布时间】:2020-03-19 06:57:52
【问题描述】:

我有两个公司的产品 JSON 列表,AppleWindows。下面是我的 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"
  }
]

我正在尝试创建AppleMicrosoft 类别的列表视图。但在我当前的列表视图中,它显示了 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();
  }

上面的代码加载了两家公司的所有产品。但是如何只加载AppleMicrosoft 的产品呢?

这是我的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'],
                    ),
                ),
            );
        }
    ),
),

【问题讨论】:

  • 显示你的代码,你如何处理data。根据您的需要检查data[i]['category'] 是否等于“Microsoft”或“Apple”
  • 嗨!我添加了ListView@OMiShah

标签: json flutter dart


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 很高兴为您提供帮助?
【解决方案2】:

您可以删除 Apple 或 Microsoft 以外的项目:

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

另见List Dartdoc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多