如何过滤地图列表以创建另一个地图列表作为搜索功能的结果

Posted

技术标签:

【中文标题】如何过滤地图列表以创建另一个地图列表作为搜索功能的结果【英文标题】:How to filter a List of Map for creating another List of Map as the result of a search functionality 【发布时间】:2021-05-04 19:21:29 【问题描述】:

我正在尝试在我的应用中实现一个搜索功能,用于在地图列表中的多个条目之间进行过滤。

我拥有的数据结构是:

[Entry: Accident , Definition: An unexpected event or circumstance without deliberate intent., Entry: Accident Insurance , Definition: Insurance for unforeseen bodily injury., Entry: Accident Only , Definition: An insurance contract that provides coverage, singly or in combination, for death, dismemberment, disability, or hospital and medical care caused by or necessitated as a result of accident or specified kinds of accident., Entry: Accident Only or AD&D , Definition: Policies providing coverage, singly or in combination, for death, dismemberment, disability, or hospital and medical care caused by or necessitated as a result of accident or specified kinds of accidents. Types of coverage include student accident, sports accident, travel accident, blanket accident, specific accident or accidental death and dismemberment (ad&d). ... etc, etc.  ]

这些是 .json 文件的内容:

[
        
            "Entry": "Accident ",
            "Definition": "An unexpected event or circumstance without deliberate intent."
        ,
        
            "Entry": "Accident Insurance ",
            "Definition": "Insurance for unforeseen bodily injury."
        ,
        [... and looooots of many other "Entry", "Definition" pairs like these]
        
            "Entry": "Written Premium ",
            "Definition": "The contractually determined amount charged by the reporting entity to the policyholder for the effective period of the contract based on the expectation of risk, policy benefits, and expenses associated with the coverage provided by the terms of the insurance contract."
        
]


每个地图条目都会创建一个带有相关定义的按钮。

向用户查询搜索查询以仅获取满足查询结果的按钮。

我包含我正在尝试实现的 .dart 文件:

import 'package:flutter/material.dart';
import 'listentries.dart';
import 'destination.dart';
import 'dart:convert';

// ignore: must_be_immutable
class searchScreen extends StatefulWidget 
  final String searchTerm;
  searchScreen(this.searchTerm);

  @override
  _SearchScreenState createState() => new _SearchScreenState();


class _SearchScreenState extends State<searchScreen> 
  @override
  Widget build(BuildContext context) 
    final widgetElements = new ListEntries(); // From listentries.dart
    var searchedItems =
        widgetElements; // Copy from widgetElements filter out from here
    var query;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text(
          "Search your term",
          style: TextStyle(fontSize: 20),
        ),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (query) 
                  //search is done here
                  //  filterSearchResults(query);
                ,
                decoration: InputDecoration(
                  labelText: 'Search',
                  hintText: 'Search your term',
                  suffixIcon: Icon(Icons.search),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(25.0),
                    ),
                  ),
                ),
              ),
            ),
            Expanded(
              child: FutureBuilder(
                future: DefaultAssetBundle.of(context)
                    .loadString('assets/data.json'),
                builder: (context, snapshot) 
                  var entries = json.decode(snapshot.data.toString());

                  final item = entries.where((e) => e['Entry'] == 'Accident'); //Accident will be changed with query
                  print(item);
                  print(entries);

                  return ListView.builder(
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) 
                      var entrada = entries[index];
                      //print(entrada);

                      return Container(
                        margin: EdgeInsets.symmetric(vertical: 2.0),
                        color: Colors.transparent,
                        width: MediaQuery.of(context).size.width,
                        height: 60,
                        child: RaisedButton(
                          shape: new RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(30.0),
                          ),
                          onPressed: () 
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => Destination(
                                  entry: entrada['Entry'],
                                  definition: entrada['Definition'],
                                ),
                              ),
                            );
                          ,
                          color: Colors.blue[900],
                          child: Text(
                            entrada['Entry'],
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Raleway',
                              fontSize: 18.0,
                            ),
                          ),
                        ),
                      );
                    ,
                    itemCount: entries == null ? 0 : entries.length,
                  );
                ,
              ),
              //child: searchedItems,
            ),
          ],
        ),
      ),
    );
  


我看到的问题是过滤结果(项目)是空的,它应该包含与“事故”相关的条目。

您能帮我实现这个搜索功能吗? 提前致谢

【问题讨论】:

由于您的问题似乎与final item = entries.where((e) =&gt; e['Entry'] == 'Accident'); 有关,请尝试缩小问题的描述和代码示例。 ` 【参考方案1】:

添加.toList() 以创建新列表

final item = entries.where((e) => e['Entry'] == 'Accident').toList();

【讨论】:

【参考方案2】:

以下是描述如何过滤项目的精简代码示例:

final List<Map<String, String>> items = [
  'Entry': 'Accident', 'Definition': 'Accident description.',
  'Entry': 'Accident Insurance', 'Definition': 'Insurance description.',
];
void main() 
  final results = items.where((item) => item['Entry'] == 'Accident');
  print(results);
  // Iterable<Map<String, String>> (Entry: Accident, Definition: An unexpected event or circumstance without deliberate intent.)
  final result = results.first;
  print(result);
  // Map<String, String> Entry: Accident, Definition: An unexpected event or circumstance without deliberate intent.

请注意,where 返回一个 Iterable。您可以使用toList() 获取地图列表。


这是一个与您之前所做的更接近的 Flutter 示例应用程序:

import 'dart:convert';

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyWidget()));

class MyWidget extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: FutureBuilder(
        future:
            DefaultAssetBundle.of(context).loadString('assets/entries.json'),
        builder: (context, snapshot) 
          final items = json.decode(snapshot.data.toString());
          final result =
              items.where((item) => item['Entry'] == 'Accident').first;
          return Column(
            children: [
              Text('Accident Definition:'),
              Text(result['Definition']),
            ],
          );
        ,
      ),
    );
  

我使用的 JSON 文件在这里:

[
  
    "Entry": "Accident",
    "Definition": "Accident description."
  ,
  
    "Entry": "Accident Insurance",
    "Definition": "Insurance description."
  
]

【讨论】:

发生了一些非常奇怪的事情,因为当我使用你在 android Studio 中包含的代码时,我在“结果”中得到的结果是空的。如果我使用您包含在dart.dev/#try-dart 的飞镖垫中的代码,它会按预期工作。这怎么可能?取决于你把代码放在哪里,它可以工作还是不工作......这让我很困惑! 我发现有什么区别:我从 json.decode(snapshot.data.toString()); 得到的数据结构;是 List,而不是 List>' 我需要能够从 json.decode(snapshot.data.toString()); 的输出中过滤 你能举一个过滤 json.decode(snapshot.data.toString()); 输出的例子吗?那是一个 List ? 另一种可能性是将 List 转换为 List> ,在这种情况下,您的代码将起作用。 你的 JSON 文件的内容是什么?我添加了一个带有 JSON 文件的 Flutter 示例应用程序。

以上是关于如何过滤地图列表以创建另一个地图列表作为搜索功能的结果的主要内容,如果未能解决你的问题,请参考以下文章

如何在返回小部件之前遍历列表以创建地图?颤振 - 飞镖

我正在尝试创建一个带有位置键的地图,其中包含一个双精度列表作为坐标,但我收到一个错误

使用字典 get() 作为函数从地图创建 Python 列表与使用 for 循环创建字典 get() 列表

mapboxGL列表和地图联动

mapboxGL列表和地图联动

如何实现一个小的静态地图预览作为列表图标?