flutter - Flutter - 使用来自 SQFlite 的数据的即时过滤器(搜索)ListView
问题描述
我有一个Listview
和一个Textfield
用作搜索栏(我还应该提到每个都属于不同的类)我试图在用户键入时立即过滤列表视图
我在正确的方向上取得了进展,但问题是我正在寻找类似于这个例子的东西mList.contains(userSearch)
我目前所拥有的并不完全满足要求,它会搜索但只有当用户停止输入时,它才不会检测到文本字段上的实时变化。
从 SQFlite 数据库获取数据:
//getting full list
Future<List<Word>> getAllWords() async {
final db = await database;
var response = await db.query(TABLE_WORDS);
List<Word> list = response.map((c) => Word.fromMap(c)).toList();
return list;
}
//getting search results
Future<List<Word>> searchResults(String userSearch) async {
final db = await database;
var response = await db.query(TABLE_WORDS, where: '$COL_ENGLISH_WORD = ? OR $COL_GERMAN_WORD = ?', whereArgs: [userSearch, userSearch]);
List<Word> list = response.map((c) => Word.fromMap(c)).toList();
return list;
}
现在是我显示列表和搜索栏的页面:
String userSearchInput = "";
TextEditingController _searchInputController = TextEditingController();
class FullList extends StatefulWidget {
@override
_FullListState createState() => _FullListState();
}
class _FullListState extends State<FullList> {
@override
void initState() {
search(String userInput){
setState(() {
userInput = _searchInputController.text;
if(userInput.isEmpty){
return;
}else{
userSearchInput = userInput;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
primary: true,
title: InkWell(
splashColor: gradientStart,
child: TextField(
autofocus: false,
enableInteractiveSelection: false,
controller: _searchInputController,
onChanged: search,
decoration: InputDecoration(hintText: "Search"),
),
),
),
body: Container(
height: MediaQuery.of(context).size.height,
child: SafeArea(
child: ListPage(),
),
),
);
}
}
//The class that has the listview
class ListPage extends StatefulWidget {
@override
_ListPageState createState() => _ListPageState();
}
class _ListPageState extends State<ListPage> {
DatabaseHelper databaseHelper;
@override
void initState() {
databaseHelper = DatabaseHelper.databaseHelper;
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder<List<Word>>(
future: _searchInputController.text.isEmpty ? databaseHelper.getAllWords() : databaseHelper.searchResults(userSearchInput),
builder: (BuildContext context, AsyncSnapshot<List<Word>> snapshot){
if(snapshot.hasData){
return ListView.builder(
physics: const AlwaysScrollableScrollPhysics (),
shrinkWrap: true,
reverse: false,
controller: _scrollController,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {/*take action*/},
child: AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 300),
child: SlideAnimation(
verticalOffset: 50.0,
child: FadeInAnimation(
child: listChild(snapshot.data[index].eng, snapshot.data[index].ger),
),
),
),
);
},
);
}
return Center(
child: CircularProgressIndicator()
);
}
),
);
}
}
问题:如何更改它以便能够在用户键入时立即过滤列表?
解决方案
我认为问题是你的 initState()。你应该把它从 initState 中移走。另外,你可以这样解决;首先,定义2个列表,
List<Word> list = List<Word>();
List<Word> filteredList = List<Word>();
然后,当您从快照中获取数据时,将您获得的列表分配给您定义的列表。像这样;
if(snapshot.hasData){
if(!doItJustOnce){ //You should define a bool like (bool doItJustOnce = false;) on your state.
list = snapshot.data;
filteredList = list;
doItJustOnce = !doItJustOnce; //this line helps to do just once.
}
return ListView.builder(
...
然后,添加您的列表
itemCount: filteredList.length,
和这个;
FadeInAnimation(
child: listChild(filteredList[index].eng, filteredList[index].nor),
)
最后,你应该像这样做一个 void;
void _filterList(value) {
setState(() {
filteredList = list.where((text) => text.fileName.toLowerCase().contains(value.toLowerCase())).toList();
});
}
并添加您的 TextField 的 onChanged;
onChanged: (value) {
_filterList(value);
},
如果您重置列表,只需写下这些行;
setState(() {
filteredList = list;
});
你可以试试你的代码;
import 'package:flutter/material.dart';
class FullList extends StatefulWidget {
@override
_FullListState createState() => _FullListState();
}
class _FullListState extends State<FullList> {
String userSearchInput = "";
TextEditingController _searchInputController = TextEditingController();
DatabaseHelper databaseHelper;
List<Word> list = List<Word>();
List<Word> filteredList = List<Word>();
bool doItJustOnce = false;
void _filterList(value) {
setState(() {
filteredList = list
.where((text) => text.eng.toLowerCase().contains(value.toLowerCase()))
.toList(); // I don't understand your Word list.
});
}
@override
void initState() {
databaseHelper = DatabaseHelper.databaseHelper;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
primary: true,
title: InkWell(
splashColor: gradientStart,
child: TextField(
autofocus: false,
enableInteractiveSelection: false,
controller: _searchInputController,
onChanged: (value) {
_filterList(value);
},
decoration: InputDecoration(hintText: "Search"),
),
),
),
body: Container(
height: MediaQuery.of(context).size.height,
child: SafeArea(
child: Container(
child: FutureBuilder<List<Word>>(
future: databaseHelper.getAllWords(),
builder: (BuildContext context, AsyncSnapshot<List<Word>> snapshot) {
if (snapshot.hasData) {
if (!doItJustOnce) {
//You should define a bool like (bool doItJustOnce = false;) on your state.
list = snapshot.data;
filteredList = list;
doItJustOnce = !doItJustOnce; //this line helps to do just once.
}
return ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
shrinkWrap: true,
reverse: false,
controller: _scrollController,
itemCount: filteredList.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
/*take action*/
},
child: AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 300),
child: SlideAnimation(
verticalOffset: 50.0,
child: FadeInAnimation(
child: listChild(filteredList[index].eng, filteredList[index].ger),
),
),
),
);
},
);
}
return Center(child: CircularProgressIndicator());
}),
),
),
),
);
}
}
推荐阅读
- swift - 如何自定义 Realm 平台的 SyncUser?
- ios - SWIFT:应用程序是为 RTL 语言设计的,但是当我在基于 RTL 的语言上运行时,它会镜像
- c++ - 使用模板重载函数
- javascript - 有没有地方可以测试代码是否符合 ES5/安全?
- reporting-services - SSRS 条件最大值
- php - 输出缓冲转储空字符串,2560 字符长
- java - 使用 ArrayAdapter 不适用于片段
- javascript - crypto-js 错误的 des-ecb 解码
- javascript - 如何在 IE 中检测/定位“忽略网页上指定的颜色”设置?
- scala - Option[Int] 作为循环中的索引