gpt4 book ai didi

flutter - 构建上下文 : the meaning of nearest enclosing?

转载 作者:IT王子 更新时间:2023-10-29 06:57:09 29 4
gpt4 key购买 nike

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

This can lead to some tricky cases. For example, Theme.of(context) looks for the nearest enclosing Theme of the given build context. ...

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

最佳答案

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

In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method.

好吧,这不是一种非常有用的语言。想象一下:

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 - 构建上下文 : the meaning of nearest enclosing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56027446/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com