flutter 里面的 autoComplete 是通过插件 flutter_typeahead 实现。
开源地址: https://github.com/AbdulRahmanAlHamali/flutter_typeahead
1.首先在pubspec.yaml里添加配置:
flutter_typeahead: 0.4.1
2.在dart 文件头导入:
import 'package:flutter_typeahead/flutter_typeahead.dart';
3.接上一篇登录页面,修改第一个学校选择框为autoComplete:
定义数据,也可以是通过后台查询进行匹配,或者通过方法处理后返回数据。
var SerVerConfig = [
{
"name": "学校一",
"code": "one",
},
{
"name": "学校二",
"code": "two",
},
{
"name": "学校三",
"code": "three",
}
];
/*****
* login page school input
* ***/
Widget loginSchoolInput(BuildContext context){
return new Padding(
padding: EdgeInsets.fromLTRB(20.0, 0.0 ,20.0, 0.0),
child: new Stack(
alignment: Alignment(1.0, 1.0),
children: <Widget>[
new Row(
children: <Widget>[
new Padding(
padding: EdgeInsets.all(5.0),
child: new Image.asset(
"images/icon_username.png",
width: 40.0,
height: 40.0,
fit: BoxFit.fill,
),
),
new Expanded(
/*************修改的地方**********************/
child: new TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
style: DefaultTextStyle.of(context).style.copyWith(
fontStyle: FontStyle.italic
),
decoration: InputDecoration(
border: OutlineInputBorder()
)
),
suggestionsCallback: (pattern) async {
return SerVerConfig; //静态数据
// return await BackendService.getSuggestions(pattern); //查询返回数据
},
itemBuilder: (context, suggestion) {
return ListTile(
leading: Icon(Icons.shopping_cart),
title: Text(suggestion['name']), //返回数据里的属性名
);
},
onSuggestionSelected: (suggestion) {
Navigator.of(context).push(MaterialPageRoute(
// builder: (context) => ProductPage(product: suggestion)
));
},
)),
],
),
new IconButton(
icon: new Icon(Icons.clear),
onPressed: (){
schoolController.clear();
} ,
)
],
),
);
}
根据官方说明,需要修改的地方就这两处,基本就满足需求了,有其他需求可以自行在研究。
4.效果ok