我具有以下dart继承结构:
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访问超类中变量的值时,出现以下编译器错误:
在初始化器中只能访问静态成员
我还能如何访问该值?
更新 遵循建议的答案后,文本现在停留在应用栏中。确实会根据以下代码进行更改:
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。但是,不会生成文本字段。应用栏仍显示标题。我没有进行热重装或热重启。我实际上完全重启了。
答案 0 :(得分:1)
这是您需要做的一种整洁的方式
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
}
}