如何从外部访问有状态小部件的属性/方法?

问题描述 投票:0回答:1

我需要从外部访问_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;
   }
}
dart flutter
1个回答
0
投票

如果我理解你的问题,那么你有两个小部件。让我们称他们为Widget AWidget 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

© www.soinside.com 2019 - 2024. All rights reserved.