如何过滤List of Map以创建另一个List of Map作为搜索功能的结果



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

数据结构是:

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

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

你能帮忙实现这个搜索功能吗?提前感谢

add.toList()创建新列表

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

下面是一个简化的代码示例,描述如何过滤条目:

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."
}
]

最新更新