【发布时间】:2018-12-25 11:00:29
【问题描述】:
我在顶部有一个 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 的上下文。如果我使用对孩子可用的上下文,则工作表会在我的 UI 的错误底部锚点处弹出。现在,孩子已经可以通过 GlobalKey 与顶部小部件进行通信了。但是,在顶部小部件的另一种方法中,我只能访问其一般上下文。将此上下文传递给 showModalBottomSheet 会引发空指针。
经过大量研究和反复试验,我想出的唯一解决方案是在构建方法中缓存上下文 (_builderContext = context;),然后使用这个缓存的上下文将其传递到我的另一个顶部小部件中的 showModalBottomSheet方法:
openBottomSheet() {
if (_builderContext != null) {
showModalBottomSheet(
context: _builderContext,
builder: (context) {
return // some bottom sheet content;
});
}
}
目前,这似乎工作得很好,但我想知道是否有更清洁的方法来做到这一点?
这个问题可以概括为我一般如何访问子小部件中的上下文。我尝试提出一个 InheritedWidget 解决方案,但无法真正理解如何以某种方式使 Builder 成为继承的小部件,然后将其用于我的问题。
非常感谢任何想法。
【问题讨论】:
-
你应该只有一个
MaterialApp实例 -
我遇到了关于模式和 InheritedWidget 的类似问题 - 解决方案是在我的应用程序的根目录中使用“InheritedWidget”(即/来自 main.dart)
标签: widget flutter bottom-sheet