我需要从外部访问_InnerBlockState类中的方法setBlockText()来更改Text Widget的标签,例如: 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;
}
}
如果我理解你的问题,那么你有两个小部件。让我们称他们为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