我需要从外部访问_InnerBlockState类内的setBlockText()方法以更改文本小部件的标签,例如OuterBlock.setInnerBlockLabel()。这有可能吗?下面仅提供一个小示例。
class OuterBlock {
Widget column;
Widget innerBlock;
OuterBlock() {
innerBlock = new InnerBlock();
initColumn();
}
initColumn() {
column = new Column(
children: <Widget>[
innerBlock
]
}
setInnerBlockLabel() {
// TODO set the text/ label from the Text Widget of the innerBlock
}
}
class InnerBlock extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _InnerBlockState();
}
}
class _InnerBlockState extends State<InnerBlock> {
String label = '';
@override
Widget build(BuildContext context) {
return Container(
child: Text(label)
);
}
void setBlockText(String label) {
this.label= label;
}
}
答案 0 :(得分:0)
如果我正确理解了您的问题,那么您有两个小部件。让我们称它们为Widget A
和Widget B
。
Widget B
具有文本变量,并由Widget A
使用。您要更改Widget A
中的文本变量。
我的解决方案:将变量传递给Widget B
。
代码:
// shouldn't your OuterBlock be a widget?
class OuterBlock {
Widget column;
Widget innerBlock;
String yourLabel;
OuterBlock() {
innerBlock = new InnerBlock(textVariable: yourLabel);
initColumn();
}
initColumn() {
column = new Column(children: <Widget>[innerBlock]);
}
setInnerBlockLabel() {
yourLabel = "fancy Label"; // your fancy business logic :P
}
}
class InnerBlock extends StatefulWidget {
final String textVariable;
InnerBlock({Key key, this.textVariable}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _InnerBlockState();
}
}
class _InnerBlockState extends State<InnerBlock> {
@override
Widget build(BuildContext context) {
return Container(child: Text(widget.textVariable));
}
}
您的Glup3