我正在创建一个搜索栏,我需要将有状态的小部件的状态传播到其子级。
当我搜索一些字符串时,必须将编辑后的文本传递给实现ListView的子窗口小部件。
这是父窗口小部件:
import ...
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final TextEditingController _filter = new TextEditingController();
Widget _appBarTitle = new Text('My App');
bool _searching = false;
String _searchText = "";
@override
void initState() {
super.initState();
_filter.addListener(() {
if (_filter.text.isEmpty) {
setState(() {
_searchText = "";
});
} else {
setState(() {
_searchText = _filter.text;
});
}
});
}
void _onSearchBackPressed() {
setState(() {
_searching = !_searching;
_appBarTitle = _buildAppBar();
});
}
Widget _buildBackIcon() {
if (_searching) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: _onSearchBackPressed,
);
} else {
return null;
}
}
Widget _buildAppBar() {
if (_searching) {
return TextField(
controller: _filter
);
} else {
return Text('My App');
}
}
List<Widget> _buildActions() {
if (_searching) {
return null;
} else {
return <Widget>[
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: _onSearchBackPressed,
),
];
}
}
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, AppState>(
converter: (store) => store.state,
builder: (context, appState) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: _appBarTitle,
leading: _buildBackIcon(),
actions: _buildActions()
),
body: new DefaultTabController(
length: 1,
child: new Column(
children: <Widget>[
ChildWidget(appState: appState, filter: _searchText), // <-- HERE I NEED TO PROPAGATE THE PARENT STATE
],
),
),
),
);
},
);
}
}
如您现在所见,我只是将_searchText
值传递给ChildWidget
子构造函数。
这是好方法还是我做错了?
当_searchText
发生更改时,ChildWidget
是否正确重建?