使用 json 数据自动完成建议和搜索
Posted
技术标签:
【中文标题】使用 json 数据自动完成建议和搜索【英文标题】:Autocomplete suggestion and search using json data 【发布时间】:2019-05-01 05:33:33 【问题描述】:当用户在文本字段中键入时,我想在 list
中显示来自本地 json 的数据作为建议。显示的建议应基于与要显示的文本相关联的id
。
不知何故,我无法实现在 UI 中显示数据以及如何构建将在list
中显示建议的小部件层次结构。不知道我在这里错过了什么。寻求指导。我希望达到的最终结果是:
Json sn-p:
"data": [
"serviceCategory": "ELECTRICAL",
"serviceCategoryDesc": "Electrical",
"serviceCategoryId": 3,
"autocompleteTerm": "Accent Lighting Installation",
"category": "IMPROVEMENT",
例如:如果用户键入electrical
,则autocompleteterm
值应显示在list
中。
为此,我创建了模型类并获取了正确显示在console
中的数据。
class Categories
String serviceCategory;
String servCategoryDesc;
int id;
String autocompleteterm;
String category;
String desc;
Categories(
this.serviceCategory,
this.servCategoryDesc,
this.id,
this.autocompleteterm,
this.category,
this.desc
);
factory Categories.fromJson(Map<String, dynamic> parsedJson)
return Categories(
serviceCategory: parsedJson['serviceCategory'] as String,
servCategoryDesc: parsedJson['serviceCategoryDesc'] as String,
id: parsedJson['serviceCategoryId'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
category: parsedJson['category'] as String,
desc: parsedJson['description'] as String
);
代码:
// Get json result and convert it to model. Then add
Future<String> getUserDetails() async
String jsonData = await DefaultAssetBundle.of(context).loadString('assets/services.json');
Map data = json.decode(jsonData);
print(data);
setState(()
final List<Categories> items = (data['data'] as List).map((i) => new Categories.fromJson(i)).toList();
for (final item in items)
print(item.autocompleteterm);
);
GlobalKey<AutoCompleteTextFieldState<Categories>> key = new GlobalKey();
get categories => List<Categories>();
AutoCompleteTextField textField;
String currentText = "";
List<Categories> added = [];
@override
void initState()
textField = AutoCompleteTextField<Categories>
(style: new TextStyle(
color: Colors.white,
fontSize: 16.0),
decoration: new InputDecoration(
suffixIcon: Container(
width: 85.0,
height: 60.0,
color:Colors.green,
child: new IconButton(
icon: new Image.asset('assets/search_icon_ivory.png',color: Colors.white,
height: 18.0,),
onPressed: (),
),
),
fillColor: Colors.black,
contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
filled: true,
hintText: 'Search',
hintStyle: TextStyle(
color: Colors.white
)
),
itemSubmitted: null,
submitOnSuggestionTap: true,
clearOnSubmit: true,
textChanged: (item)
currentText = item;
,
textSubmitted: (item)
setState(()
currentText = item;
added.add(widget.categories.firstWhere((i) => i.autocompleteterm.toLowerCase().contains(currentText)));
);
,
key: key,
suggestions: widget.categories,
itemBuilder: (context, item)
return new Padding(
padding: EdgeInsets.all(8.0), child: new Text(item.autocompleteterm),
);
,
itemSorter: (a,b)
return a.autocompleteterm.compareTo(b.autocompleteterm);
,
itemFilter: (item, query)
return item.autocompleteterm.toLowerCase().startsWith(query.toLowerCase());
);
super.initState();
_getUser();
getUserDetails();
@override
Widget build(BuildContext context)
Column body = new Column(
children: <Widget>[
ListTile(
title: textField,
)
],
);
body.children.addAll(added.map((item)
return ListTile(title: Text(item.autocompleteterm),
);
)
);
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: Color(0xFF13212C),
appBar: AppBar(
title: Text('Demo'),
),
drawer: appDrawer(),
body: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Column(
children: <Widget>[
textField,
]
),
【问题讨论】:
How to hook up data from local json to achieve search with autocomplete text in list?的可能重复 这和***.com/questions/53429467/…是同一个问题吗? 是的,和这些问题一样。我已经尝试过,但似乎这个包太有限了,无法使用对象而不是字符串值来完全实现。建议改用material_search
。
你指的是哪个包?
autocomplete_field - 它可能会完成,但我失败了,而是建议使用material_search
。话说,它是一个小时前更新的,所以也许是这样?
【参考方案1】:
autocomplete_field
包自提出此问题以来已更新,现在允许使用字符串以外的对象:
主页:
import 'package:flutter/material.dart';
import 'package:hello_world/category.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
class HomePage extends StatefulWidget
@override
_HomePageState createState() => new _HomePageState();
class _HomePageState extends State<HomePage>
List<Category> added = [];
String currentText = "";
GlobalKey<AutoCompleteTextFieldState<Category>> key = new GlobalKey();
AutoCompleteTextField textField;
@override void initState()
textField = new AutoCompleteTextField<Category>(
decoration: new InputDecoration(
hintText: "Search Item",
),
key: key,
submitOnSuggestionTap: true,
clearOnSubmit: true,
suggestions: CategoryViewModel.categories,
textInputAction: TextInputAction.go,
textChanged: (item)
currentText = item;
,
itemSubmitted: (item)
setState(()
currentText = item.autocompleteterm;
added.add(item);
currentText = "";
);
,
itemBuilder: (context, item)
return new Padding(
padding: EdgeInsets.all(8.0), child: new Text(item.autocompleteterm));
,
itemSorter: (a, b)
return a.autocompleteterm.compareTo(b.autocompleteterm);
,
itemFilter: (item, query)
return item.autocompleteterm.toLowerCase().startsWith(query.toLowerCase());
);
super.initState();
@override
Widget build(BuildContext context)
Column body = new Column(children: [
new ListTile(
title: textField,
trailing: new IconButton(
icon: new Icon(Icons.add),
onPressed: ()
setState(()
if (currentText != "")
added.add(CategoryViewModel.categories.firstWhere((i) => i.autocompleteterm.toLowerCase().contains(currentText)));
textField.clear();
currentText = "";
);
))
]);
body.children.addAll(added.map((item)
return ListTile(title: Text(item.autocompleteterm), subtitle: Text(item.serviceCategory));
));
return body;
类别类:
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
class Category
String serviceCategory;
String servCategoryDesc;
int id;
String autocompleteterm;
Category(
this.serviceCategory,
this.servCategoryDesc,
this.id,
this.autocompleteterm);
factory Category.fromJson(Map<String, dynamic> parsedJson)
return new Category(
serviceCategory: parsedJson['serviceCategory'],
servCategoryDesc: parsedJson['serviceCategoryDesc'],
id: parsedJson['serviceCategoryId'],
autocompleteterm: parsedJson['autocompleteTerm']);
class CategoryViewModel
static List<Category> categories;
static Future loadCategories() async
try
categories = new List<Category>();
String jsonString = await rootBundle.loadString('assets/categories.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['data'] as List;
for (int i = 0; i < categoryJson.length; i++)
categories.add(new Category.fromJson(categoryJson[i]));
catch (e)
print(e);
主要加载数据:
void main() async
await CategoryViewModel.loadCategories();
runApp(App());
请注意,有几种方法可以从 JSON 加载数据,但我发现这种方法对于简单的演示来说是最容易做到的。
【讨论】:
太棒了.. 我试图用我的目标代码来模拟这个解决方案,并在我点击textfield
的那一刻得到The method 'map' was called on null. Receiver: null Tried calling: map<Row>(Closure: (Categories) => Row)
。你介意看看这个吗? pastebin.com/egEeUVsr@SnakeyHips
您需要在您的runApp
方法之前运行CategoryViewModel.loadCategories
,以便在您的应用程序进入您的main
方法之前加载数据。我现在将我的代码添加到帖子中。
很好,就我而言,我必须从initState()
运行CategoryViewModel.loadCategories
。该解决方案完美运行。 @SnakeyHips
很高兴你得到它的工作和很好的时机,他们最近更新了软件包以允许这样做!
在类似的行上,我想显示从textfield
列表中选择的建议文本。为此,在 itemSubmitted
方法中,我做了 setState(() currentText = item.autocompleteterm; );
。它正确打印了值,但是如何在 textField
中设置该值?我需要使用textEditingController
吗? @SnakeyHips以上是关于使用 json 数据自动完成建议和搜索的主要内容,如果未能解决你的问题,请参考以下文章
使用 Google PLACES Api 搜索查看自动完成建议