无法在flutter中过滤listview.builder的列表

时间:2020-09-14 13:17:02

标签: json flutter dart filter flutter-listview

我正在尝试用where执行以下调用时过滤JSON数据,但出现错误

List filterproducts=[];
    filterproducts.addAll(widget.bomdatareceived[0]['bom_items'][0]['proc_code'].where((element) => element.contains(widget.processCode)).toList());

错误

    Class 'String' has no instance method 'where'.
Receiver: "61"
Tried calling: where(Closure: (dynamic) => dynamic)

例如,widget.proc_code61,例如下面的JSON数据

JSON数据

"bom_items": [
               {
                     
                   "proc_code": "61",
                   "name": "SPINNING",
                   "bom_catalog_item": "327",
                  },
                  {
                     
                   "proc_code": "61",
                   "name": "SPINNING",
                   "bom_catalog_item": "390",
                   },
                   {
                     
                    "proc_code": "65",
                    "name": "DYING",
                    "bom_catalog_item": "1056",
                   }
                   ]

上面的JSON数据在列表中,我想在此ListView.builder中实现过滤器类的东西,以仅列出具有相同proc_code的那些元素,我不在屏幕上实现任何搜索栏类的东西。我正在从上一个屏幕接收proc_code的值,并希望构建具有相同proc_code的列表。

请指导我如何解决此问题。

1 个答案:

答案 0 :(得分:1)

您需要执行以下操作:

void main() {
final recievedItems =  { 
              "bom_items": [
               {
                     
                   "proc_code": "61",
                   "name": "SPINNING",
                   "bom_catalog_item": "327",
                  },
                  {
                     
                   "proc_code": "61",
                   "name": "SPINNING",
                   "bom_catalog_item": "390",
                   },
                   {
                     
                    "proc_code": "65",
                    "name": "DYING",
                    "bom_catalog_item": "1056",
                   }
                     ],
             };
  
  
  List filterproducts=[];
    filterproducts.addAll(recievedItems['bom_items'].where((element) => element.containsValue("61")).toList());
  print(filterproducts);  
}

这将返回包含proc_code : 61的项目:

[{proc_code: 61, name: SPINNING, bom_catalog_item: 327}, {proc_code: 61, name: SPINNING, bom_catalog_item: 390}]

https://dartpad.dev/6e5efe3339d6ca62e2f42c557dfda012