所以我正在关注一个教程,我想在联系人列表页面的顶部添加一个搜索栏,但我似乎无法让搜索栏显示在我的应用程序中。我最初能够在我的代码中使用搜索栏,但它不会像使用它那样出现。我相信它会与结构有关,但任何建议都会很棒,我似乎无法做到正确。
我们不需要_SearchBar
类。我们必须合并AppBar
和_SearchBar
的ContactsPage
。我们必须将ContactsPage
设为Stateful
,它将变量表示为
Icon actionIcon
Widget appBarTitle
更新代码:
import 'package:flutter/material.dart';
class ContactsPage extends StatefulWidget {
Widget appBarTitle = new Text("Contacts");
Icon actionIcon = new Icon(Icons.search);
@override
State<StatefulWidget> createState() {
return new _ContactPage();
}
}
class _ContactPage extends State<ContactsPage> {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: widget.appBarTitle,
actions: <Widget>[
new IconButton(
icon: widget.actionIcon,
onPressed: () {
setState(() {
if (widget.actionIcon.icon == Icons.search) {
widget.actionIcon = new Icon(Icons.close);
widget.appBarTitle = new TextField(
style: new TextStyle(
color: Colors.white,
),
decoration: new InputDecoration(
prefixIcon:
new Icon(Icons.search, color: Colors.white),
hintText: "Search...",
hintStyle: new TextStyle(color: Colors.white)),
onChanged: (value) {
print(value);
//filter your contact list based on value
},
);
} else {
widget.actionIcon =
new Icon(Icons.search); //reset to initial state
widget.appBarTitle = new Text("Contacts");
}
});
},
),
],
),
body: new Text("contact list")),
// replace the body with your contacts list view
);
}
}
void main() {
runApp(new ContactsPage());
}