如何访问其他小部件的成员

时间:2019-11-29 19:33:08

标签: flutter dart

我有两个班级class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.rnn_cell = nn.RNNCell(input_size, hidden_size) self.fc = nn.Linear(hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, x): """ x: size [seq_length, 1, input_size] """ h = torch.zeros(x.size(1), self.hidden_size) for i in range(x.size(0)): ### START YOUR CODE ### h = self.rnn_cell(x[i,:,:], h) ### END YOUR CODE ### ### START YOUR CODE ### # Hint: first call fc, then call softmax out = self.fc(h) out = self.softmax(out) ### END YOUR CODE ### return out MyHomepage

BodyLayout是脚手架,其MyHomePageBodyLayout

现在我要访问child的{​​{1}}中的MyHomepage变量

有可能吗?或该怎么办?

onTapped

1 个答案:

答案 0 :(得分:1)

您试图以完全不推荐的方式访问类的私有变量。但是,有一种更好的方法可以解决您的问题。为什么不从父级传递函数?

在_MyHomePageState内部创建一个onTapped函数,并将该函数传递给BodyLayout

class _MyHomePageState extends State<MyHomePage> {
 ....
 void onTapped(context,var url) {
   // variables are accessible here
  }

@override
  void initState() {
    super.initState();
    _myLayouts = [
      new BodyLayout("latest","",key: Key('1'), onTapped: onTapped),
      new BodyLayout("pop","",key: Key('2'), onTapped: onTapped),
    ];
  }
 ....
}

现在在主体布局中捕获此参数并将其传递给onTap方法

class BodyLayout extends StatefulWidget {
  ...
  final Function onTapped;
  BodyLayout(this.mode,this.catKey,{Key key, this.onTapped}) : super(key: key);
  @override
  _BodyLayoutState createState() => _BodyLayoutState(onTapped: onTapped);
}

class _BodyLayoutState extends State<BodyLayout>{
  final Function onTapped;

  _BodyLayoutState({this.onTapped});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        ListView.builder(
          controller: _controller,
          itemCount: articles.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(articles[index].title),
              onTap: () => onTapped(context,articles[index].url),
            );
          },
        ),
      ]
    );
  }

}