【问题标题】:BuildContext: the meaning of nearest enclosing?BuildContext:最近封闭的含义?
【发布时间】:2019-09-25 09:39:42
【问题描述】:

我正在阅读文档:https://docs.flutter.io/flutter/widgets/BuildContext-class.html

这可能会导致一些棘手的情况。例如,Theme.of(context) 查找给定构建上下文最近的 enclosure 主题。 ...

enclosure 是否包含当前上下文的主题?我不明白作者指出的棘手案例。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    如果你理解了前面的说法,他们提到的棘手情况就会变得更加清楚:

    特别是,这意味着在构建方法中,构建方法的小部件的构建上下文与该构建方法返回的小部件的构建上下文不同。

    好吧,这不是一种很有帮助的语言。想象一下:

    FooWidgetA:
    属性:上下文、高度、宽度
    方法:构建

    FooWidgetB:
    属性:上下文、主题
    方法:构建

    FooWidgetB 在 FooWidgetA build 方法中构建。如果您尝试使用FooWidgetAcontext 来查找theme,它将找不到,因为FooWidgetA 在小部件树中位于上一层。

    因此,举例说明他们的棘手情况,它看起来像这样:

    class Foo extends StatelessWidget {
      @override
      Widget build(BuildContext buildMethodContext) {
        return MaterialApp(
          // Here we create the [ThemeData] that our method below will try to find
          theme: ThemeData(primaryColor: Colors.orange),
          builder: (BuildContext materialAppContext, _) {
            return RaisedButton(
              child: const Text('Get ThemeData'),
              onPressed: () {
                getThemeData(buildMethodContext);  // unsucessful
                getThemeData(materialAppContext);  // sucessful
              },
            );
          },
        );
      }
    
      ThemeData getThemeData(BuildContext context) => Theme.of(context);
    }
    

    这很棘手,因为这两个上下文是关闭的方式,很容易忘记 buildMethodContext 实际上来自父级 (Foo),因此它看不到 materialAppContext

    【讨论】:

    • 不知道Flutter中哪些东西可以有BuildContext。 1. 为什么叫buildMethodContext而不是fooContext? 2.那为什么叫materialAppContext而不是buildMethodContext? (以我目前的理解builder: 接受匿名build() 函数,不确定这是否正确。)
    • buildMethodContext 可以命名为 fooContextmaterialAppContext 不能命名为 buildMethodContext,因为我们作为参数传递的 builder 不会替换 MaterialApp 的构建器。它会在 MaterialApp 的构建器的某个地方被调用,但它不是构建器本身。
    • I don't know which things in Flutter can have BuildContext > 小部件有BuildContext。此上下文是给方法build 的上下文。这就是为什么他们被称为BuildContext
    • So from your answer, my question Does enclosing includes the Theme of current context? should be yes? > 是的。 So it works like... > 非常喜欢。它实际上包装了我们在Builder 中传递的build 方法,就像您在答案中所做的那样。看一下(注意widget.build指的是我们通过的build方法):github.com/flutter/flutter/blob/master/packages/flutter/lib/src/…
    • 没错。老实说,当我回答你的时候,我什至不知道在这一切中间有一个Builder,但是因为在这种情况下使用materialAppContextbuilderContext 没有任何区别,我不会告诉你(如果我知道的话)让事情变得更简单。
    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多