我有一个主要的 dart GridView,如下所示:
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GridView.count(crossAxisCount: 2, shrinkWrap: true, children: [
BuildButtonWithText(Icons.volume_down, "Vol Down", "VOL_DN")
.customButtonWithText(),
BuildButtonWithText(Icons.volume_up, "Vol Up", "VOL_UP")
.customButtonWithText(),
BuildButtonWithText(Icons.play_arrow, "Play/Pause", "PLAY")
.customButtonWithText(),
BuildButtonWithText(Icons.volume_mute, "Mute", "VOL_MUTE")
.customButtonWithText(),
]),
TextField(controller: status_text),
],
)),
进行按钮创建的对应类如下:
class BuildButtonWithText {
List<Column> _gridButtons = <Column>[];
IconData _iconName;
String _buttonText;
String _buttonID;
BuildButtonWithText(IconData iconName, String buttonText, String buttonID) {
this._iconName = iconName;
this._buttonText = buttonText;
this._buttonID = buttonID;
}
String get _getButtonText {
return this._buttonText;
}
String get _getButtonID {
return this._buttonID;
}
set _setButtonText(String newButtonText) {
this._buttonText = newButtonText;
}
void buttonPressHandler(String buttonID) {
log('ButtonPressed: $buttonID');
if (buttonID.compareTo("PLAY") == 0) {
this._setButtonText = "PAUSE";
}
if (buttonID.compareTo("PAUSE") == 0) {
this._setButtonText = "PLAY";
}
}
Column customButtonWithText() {
Column _button = Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(this._iconName),
onPressed: () {
buttonPressHandler(this._buttonID);
},
),
Text(_buttonText)
],
);
_gridButtons.add(_button);
return _button;
}
}
鉴于我对 Dart/Flutter 非常陌生,我想做的是,
buttonPressHandler
中,通过 Column
值从 _gridButtons
列表中搜索特定的 _buttonID
项目。我查看了 .firstWhere
函数,但无法访问该特定变量。Column
,我想根据需要修改 Text
值。上面的代码编译并运行,但文本值似乎没有变化。
答案 0 :(得分:0)
我发现我做错了。我认为这是解决这个问题的正确方法,欢迎任何其他替代方案。
创建一个 StatefulWidget
类:
class ButtonWithText extends StatefulWidget {
IconData _iconName;
String _buttonTextStr;
String _buttonID;
List<Column> _gridButtons = <Column>[];
ButtonWithText(iconName, buttonTextStr, buttonID) {
this._iconName = iconName;
this._buttonTextStr = buttonTextStr;
this._buttonID = buttonID;
}
@override
_ButtonWithTextState createState() => _ButtonWithTextState();
}
制作相应的State
类来处理逻辑:
class _ButtonWithTextState extends State<ButtonWithText> {
@override
Widget build(BuildContext context) {
Column _button = Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(widget._iconName),
onPressed: () {
buttonPressHandler(widget._buttonID);
},
),
Text(widget._buttonTextStr)
],
);
widget._gridButtons.add(_button);
return _button;
}
void buttonPressHandler(String buttonID) {
log('ButtonPressed: $buttonID');
if (buttonID.compareTo("PLAY") == 0) {
log("Pressed PLAY");
setState(() {
widget._buttonID = "PAUSE";
widget._buttonTextStr = "Pause";
});
}
if (buttonID.compareTo("PAUSE") == 0) {
log("Pressed PAUSE");
setState(() {
widget._buttonID = "PLAY";
widget._buttonTextStr = "Play";
});
}
}
}
这现在允许我正在寻找的状态更改功能。以下是帮助我解决问题的链接: