提问人:Rohan Jariwala 提问时间:12/24/2022 最后编辑:Rohan Jariwala 更新时间:1/7/2023 访问量:1539
Flutter TextFormField 建议或自动完成
Flutter TextFormField suggestion or auto complete
问:
我想在textFormField中实现建议。如下同
所以,我已经搜索过这个,但没有成功。我所拥有的任何地方都是列表中的建议。这很容易做到。如果您有任何建议,请添加您宝贵的答案和评论。
这是我的代码
Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: controller,
onFieldSubmitted: (value) {},
onChanged: (value) {
displaySuggestionInList(value);
},
),
const SizedBox(height: 30),
ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: 100,
maxWidth: 200,
minWidth: 200,
minHeight: 100,
),
child: ListView.builder(
shrinkWrap: true,
itemCount: dashboardLayouts!.length,
itemBuilder: (context, index) {
return Text((dashboardLayouts![index]['dashBoardData']
as DashboardInfo)
.commonName
.toString());
},
),
)
],
),
答:
0赞
Ibukunoluwa Naphtali
12/24/2022
#1
您需要创建一个预先输入的小部件。为此,您将首先创建普通的 List 建议 StatefulWidget。在筛选器功能上,您应该使用建议列表中的第一个值更新提示。这样,您可以调用提示值并将其放置在屏幕上的任何位置。不幸的是,flutter 不允许在输入字段中显示提示的更新。
虽然我做了一个例子让你明白这个想法。
class AutocompleteExample extends StatefulWidget {
const AutocompleteExample({super.key});
@override
State<AutocompleteExample> createState() => _AutocompleteExampleState();
}
class _AutocompleteExampleState extends State<AutocompleteExample> {
TextEditingController controller = TextEditingController();
List suggestionList = [];
String hint = "";
List<String> nameList = <String>[
'aardvark',
'bobcat',
'chameleon',
'Nathaniel Bond',
'Taylor Story',
'Lamont Padilla',
'Jamia Sun',
'Nikki Reichert',
'Tea Holguin',
'Rafael Meade',
'Mercedez Goad',
'Aileen Foltz',
'Bryant Burt',
];
void typeAheadFilter(String value) {
suggestionList.clear();
if (value.isEmpty) {
setState(() {});
return;
}
for (String name in nameList) {
if (name.toLowerCase().contains(value)) {
suggestionList.add(name);
}
}
if (suggestionList.isNotEmpty) {
var firstSuggestion = suggestionList[0];
setState(() => hint = firstSuggestion);
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: controller,
onFieldSubmitted: (value) {},
onChanged: (value) => typeAheadFilter(value),
decoration: InputDecoration(
hintText: hint,
labelText: hint.isEmpty ? "Search" : hint,
alignLabelWithHint: true,
hintTextDirection: TextDirection.rtl),
),
const SizedBox(height: 10),
if (suggestionList.isNotEmpty || controller.text.isNotEmpty) ...[
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(10),
shrinkWrap: true,
itemCount: suggestionList.length,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
return Text((suggestionList[index]));
},
),
)
] else ...[
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(10),
shrinkWrap: true,
itemCount: nameList.length,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
return Text((nameList[index]));
},
),
)
]
],
);
}
}
评论