我有一个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()
);
}
),
);
}
}
问题:如何更改它以便能够在用户键入时立即过滤列表?