【发布时间】:2021-03-11 06:16:01
【问题描述】:
我有一个 Flutter 应用程序,它可以获取在线用户列表,并在列表视图中显示数据。我试图实现一个搜索功能来搜索数据,但是每次我尝试在文本字段中输入任何内容时,整个页面都会刷新并执行 api 调用以再次获取数据。这是获取和显示数据的代码
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Prospect List"),
centerTitle: true,
),
body: prospectData(),
);
}
Widget prospectData() {
return FutureBuilder(
future: _fetchData(),
builder: (BuildContext context, AsyncSnapshot<ProspectList> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
if (snapshot.hasError)
return Text("There was an error: ${snapshot.error}");
prospectList = snapshot.data;
return ListView.builder(
itemCount: prospectList.data.length + 1,
itemBuilder: (context, i) {
if (prospectList.data.length > 0) {
return i == 0 ? _searchBar() : _prospectData(i - 1);
} else {
return Center(child: CircularProgressIndicator());
}
},
);
default:
return null;
}
});
}
_prospectData(i) {
final name =
prospectList.data[i].firstname + " " + prospectList.data[i].lastname;
final phone = prospectList.data[i].phone;
final email = prospectList.data[i].email;
return ListTile(
title: Text(
name,
style: TextStyle(fontSize: 18),
),
subtitle: Text(
phone,
style: TextStyle(fontSize: 16),
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CustomerInfo(
name: name,
phone: phone,
email: email,
))),
);
}
这是我尝试实现但无法正常工作的搜索方法
_searchBar() {
return Container(
child: Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(hintText: 'Search...'),
onChanged: (text) {
text = text.toLowerCase();
setState(() {
_prospectDisplay = prospectList.data.where((post) {
var postTitle = post.firstname.toLowerCase();
return postTitle.contains(text);
}).toList();
});
})),
);
}
编辑 我找到了我正在寻找的解决方案Here
【问题讨论】: