如何最好地从子窗口小部件访问嵌套窗口小部件的BuildContext?

时间:2018-07-17 16:43:28

标签: widget flutter bottom-sheet

我在顶部有一个StatefulWidget(我们将其称为顶部小部件),其构建功能如下所示:

@override
Widget build(BuildContext context) {
return new MaterialApp(
    color: // some color,
    theme: // some theme,
    home: new Scaffold(
        backgroundColor: // some color,
        body: new Builder(builder: (context) {
          _builderContext = context;
          return new Column(
            children: <Widget>[
              new Expanded(
                child: new MaterialApp(
                  color: // some color,
                  theme: // some theme,
                  title: 'title',
                  onGenerateRoute: _onRoute,
                  navigatorKey: _navigatorState,
                  navigatorObservers: observers,
                ),
              ),
              ... etc

现在,在_onRoute生成的子窗口小部件中的某个位置,我想用showModalBottomSheet(context, ...)来显示一个底页。但是,传递给showModalBottomSheet的上下文必须是上述构建方法中来自Builder的上下文。如果我使用孩子可用的上下文,则工作表会在用户界面的错误底部锚点弹出。现在,孩子已经可以通过GlobalKey与顶部小部件进行通信了。但是,在顶部小部件的另一种方法中,我只能访问其一般上下文。将此上下文传递给showModalBottomSheet会引发空指针。

经过大量研究和反复试验,我想出的唯一解决方案是将上下文缓存在构建方法(_builderContext = context;)中,然后使用此缓存的上下文将其传递给另一个实例中的showModalBottomSheet顶部小部件方法:

openBottomSheet() {
  if (_builderContext != null) {
    showModalBottomSheet(
        context: _builderContext,
        builder: (context) {
          return // some bottom sheet content;
        });
  }
}

就目前而言,这似乎工作得很好,但是我想知道是否有更清洁的方法来做到这一点?

这个问题可以概括为我一般如何访问子小部件中的上下文。我试着想出一个InheritedWidget解决方案,但无法真正思考如何使Builder成为继承的小部件,然后将其用于我的问题。

任何想法都值得赞赏。

1 个答案:

答案 0 :(得分:0)

如果此问题仅用于使用ModalBottomSheet,我强烈建议您使用Flushbar Plugin here进行颤动。它具有安静的灵活性,您可以在很大程度上自定义它,而不必照顾上下文和其他内容,可以根据需要对其进行编辑,即使您没有脚手架祖先,也可以在任何地方使用它。在使用底部模态板或脚手架时,需要脚手架祖先。

如果此问题仅与在父小部件中的子小部件中使用上下文有关,我建议您将其简单地传递给任何class/widget(stateful/stateless) 作为参数。它使一切安静易于使用。

相关问题