一旦搜索被清除,如何在列表视图生成器中显示原始列表——FLUTTER



我已经在列表视图生成器上实现了搜索操作,但在清除搜索栏后无法显示原始联系人列表。

class ContactsPage extends StatefulWidget {
@override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
List<Contact> _contacts = [];
List<Contact> _contactsFiltered = [];
TextEditingController searchController = TextEditingController();
@override
void initState() {
getContacts();
super.initState();
searchController.addListener(() {
filterContacts();
});
}
Future<void> getContacts() async {
final List<Contact> contacts = await ContactsService.getContacts(
withThumbnails: false,
photoHighResolution: false,
);
setState(() {
_contacts = contacts;
});
}
filterContacts() {
List<Contact> _results = [];
_results.addAll(_contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere((contact) {
String searchTerm = searchController.text.toLowerCase();
String contactName = contact.displayName!.toLowerCase();
return contactName.contains(searchTerm);
});
setState(() {
_contactsFiltered = _contacts;
});
} 
}
@override
Widget build(BuildContext context) {
bool isSearching = searchController.text.isNotEmpty;
return Scaffold(
appBar: AppBar(
title: (const Text('Contacts')),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: TextField(
controller: searchController,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
suffixIcon: Icon(
Icons.close,
),
hintText: 'Search Customer',
),
),
),
const SizedBox(
height: 6.0,
),
Align(
alignment: Alignment.topLeft,
child: TextButton(
onPressed: () {},
child: const Text(
"  + Add new Customer",
style:
TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: isSearching == true
? _contactsFiltered.length
: _contacts.length,
itemBuilder: (BuildContext context, int index) {
Contact? contact = isSearching == true
? _contactsFiltered[index]
: _contacts[index];
return ListTile(
leading: CircleAvatar(
child: Text(contact.initials()),
),
title: Text(contact.displayName ?? ''),
);
},
),
),
],
),
));
}
}

我可以根据他们的名字搜索联系人列表,但搜索并不完美。例如,如果我不小心输入了错误的名称,那么它将不会向我显示原始列表或过滤结果

您可以使用textField的onChange属性,检查值,然后将false分配给isSearching。请检查以下示例:

TextField(
controller: searchController,
onChanged: (value) {
if (value.isEmpty) {
setState(() {
isSearching = false;
});
}
},
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
suffixIcon: Icon(
Icons.close,
),
hintText: 'Search Customer',
),
),

最新更新