我有以下镖继承结构:
class MySuperList extends StatefulWidget {
final category_name;
MySuperList({this.category_name});
@override
_MySuperListState createState() => new _MySuperListState();
}
class _MySuperListState extends State<MySuperList> {
Widget appBarTitle = new Text(
widget.category_name, <== Only static members can be accessed in initializers
style: new TextStyle(color: Colors.white);
正如你所看到的,当我尝试使用widget.category_name,我得到以下编译器错误访问超类中的变量的值:
只有静态成员可以在初始化访问
我还能如何访问该值?
更新后的建议的答案后,文字现在停留在appbar。它基于变化对下面的代码:
Widget buildAppBar(BuildContext context) {
return new AppBar(centerTitle: false, title: getAppBarTitle(), actions: <Widget>[
new IconButton(
icon: icon,
onPressed: () {
this.appBarTitle = null;
setState(() {
if (this.icon.icon == Icons.search) {
this.icon = new Icon(
Icons.close,
color: Colors.white,
);
this.appBarTitle = new TextField(
controller: _controller,
autofocus: true,
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: searchOperation,
);
} else {
_handleSearchEnd();
}
});
},
),
]);
}
void _handleSearchEnd() {
setState(() {
this.icon = new Icon(
Icons.search,
color: Colors.white,
);
_isSearching = false;
this.appBarTitle = new Text(
widget.category_name,
style: new TextStyle(color: Colors.white),
);
_controller.clear();
});
}
正如你所看到的,当点击搜索图标,当我设置appBarTitle到TextField。然而,不产生文本字段。该appbar仍然显示标题。我没有做热重装或热启动。其实我做了全面的重新启动。
这就是你需要做的一种巧妙的方法
import 'package:flutter/material.dart';
class MySuperList extends StatefulWidget{
final category_name;
MySuperList({this.category_name});
@override
State<StatefulWidget> createState() {
return _MySuperListState();
}
}
class _MySuperListState extends State<MySuperList>{
bool _isSearching=false;
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(),
);
}
Widget buildAppBar(){
return AppBar(
centerTitle: false,
title: getAppBarTitle(),
actions: <Widget>[
getAction()
],
);
}
Widget getAction(){
if(_isSearching){
return IconButton(
icon: Icon(
Icons.close
),
onPressed: (){
setState(() {
_controller.clear();
_isSearching = false;
});
},
);
}else{
return IconButton(
icon: Icon(
Icons.search
),
onPressed: (){
setState(() {
_isSearching = true;
});
},
);
}
}
Widget getAppBarTitle(){
if(_isSearching){
return TextField(
controller: _controller,
autofocus: true,
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: searchOperation,
);
}else{
return Text(
widget.category_name,
style: new TextStyle(color: Colors.white)
);
}
}
searchOperation(String value){
//do what you need to onChanged
}
}