gpt4 book ai didi

flutter - 如何在flutter_typehead TypeAheadField小部件中设置字段的文本?

转载 作者:行者123 更新时间:2023-12-03 02:43:51 24 4
gpt4 key购买 nike

我是 Dart 和 Flutter 的新手,我正在尝试使用这个模块 https://github.com/AbdulRahmanAlHamali/flutter_typeahead制作具有自动完成/“提前输入”功能的文本字段。

在他们给出的示例中,当用户选择其中一个建议时,他们会将用户路由到另一个 View ,但我不想这样做。我只想将输入文本的值设置为用户选择的任何值。

这是我的代码:

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
style: DefaultTextStyle.of(context).style.copyWith(
fontStyle: FontStyle.italic
),
decoration: InputDecoration(
border: OutlineInputBorder()
)
),
suggestionsCallback: (pattern) async {
Completer<List<String>> completer = new Completer();
completer.complete(<String>["cobalt", "copper"]);
return completer.future;
},
itemBuilder: (context, suggestion){
return ListTile(
title: Text(suggestion)
);
},
onSuggestionSelected: (suggestion) {
}
)
],
),
)
);
}
}

我不知道在 onSuggestionSelected 里面放什么参数函数来实现我所描述的。

最佳答案

好的,我在我提供的同一个 github 链接上找到了解决方案,但是由于示例不是完全相同的组件( TypeAheadFormField 而不是 TypeAheadField )并且示例只是缺少的一段代码上下文,我不得不查看源代码才能理解。

以下是如何进行。这实际上适用于 TypeAheadFormFieldTypeAheadField .您必须创建一个 TextEditingController传递给 TypeAheadField 的构造函数小部件。然后你设置text TextEditingController 的属性(property)在您的 onSuggestionSelected回调方法。 TypeAheadField小部件将使用该值重绘自己,我想这就是它的工作原理。

这是有效的代码:

class _MyHomePageState extends State<MyHomePage> {

final TextEditingController _typeAheadController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
style: DefaultTextStyle.of(context).style.copyWith(
fontStyle: FontStyle.italic
),
decoration: InputDecoration(
border: OutlineInputBorder()
),
controller: this._typeAheadController
),
suggestionsCallback: (pattern) async {
Completer<List<String>> completer = new Completer();
completer.complete(<String>["cobalt", "copper"]);
return completer.future;
},
itemBuilder: (context, suggestion){
return ListTile(
title: Text(suggestion)
);
},
onSuggestionSelected: (suggestion) {
this._typeAheadController.text = suggestion;
}
)
],
),
)
);
}
}

关于flutter - 如何在flutter_typehead TypeAheadField小部件中设置字段的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com