今天會教大家如何自己製作一個簡單的搜尋功能
建立一個search_name_screen.dart的檔案,並且使用StatefulWidget
建立下方三個變數
_controller
監聽文字輸入框內容_query
儲存_controller.text的文字nameList
儲存name的列表_SearchNameScreenState()
的Function,來監聽_controller的改變filter(element)
的Function,來判斷nameList內有沒有 _controller.text
輸入的文字import 'package:flutter/material.dart';
class SearchNameScreen extends StatefulWidget {
const SearchNameScreen({Key? key}) : super(key: key);
@override
State<SearchNameScreen> createState() => _SearchNameScreenState();
}
class _SearchNameScreenState extends State<SearchNameScreen> {
final TextEditingController _controller = TextEditingController();
String _query = "";
List<String> nameList = [
'Liam',
'Olivia',
'Noah',
'Emma',
'Oliver',
'Charlotte',
'Elijah',
'Amelia',
'James',
'Ava',
'William',
'Sophia',
'Benjamin',
'Isabella',
'Lucas',
'Mia',
'Henry',
'Evelyn',
'Theodore',
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const Text(
"搜尋列表",
),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Center(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
hintText: 'Search Name',
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(20),
child: SingleChildScrollView(
child: Center(
child: Column(
children: nameList
.where((element) => _query == "" || filter(element))
.map(
(name) => Card(
color: const Color(0xFFB0D7FD),
child: ListTile(
title: Text(name),
),
),
)
.toList(),
),
),
),
),
),
],
),
);
}
_SearchNameScreenState() {
_controller.addListener(() {
setState(() {
_query = _controller.text;
});
});
}
bool filter(element) {
final nameMatched = element.toUpperCase().contains(_query.toUpperCase());
return nameMatched;
}
//filter大小寫區分版本
// bool filter(element) {
// return element.contains(_query);
// }
}