如何在flutter中访问一个与当前widget同级别的widget?
How to access a widget has the same level with the current widget in flutter?
在我的 LoginFormState 中我有
final signInFormKey = LabeledGlobalKey<FormState>("login_form");
static LoginFormState of(BuildContext context) {
return context.findAncestorStateOfType<LoginFormState>();
}
我的 MainButton 状态有这一行
LoginFormState.of(context)
.signInFormKey
.currentState
.validate()
并且它们都有相同的父级,它们的父级是堆栈小部件:
[
Builder( builder: (BuildContext context) => AnimatedOpacity(
opacity: status == 0 ? 0 : 1,
duration: Duration(milliseconds: 500),
child: LoginForm(),
),
),
MainButton(),
]
当我在 mainButton 状态下调用该函数时,它会记录以下错误:
发生错误是因为您在 MainButton
中调用了 LoginFormState.of()
方法,但它没有 LoginForm
祖先。
那是你的小部件树:
- 一些您在代码中没有post的小部件
Builder
AnimatedOpacity
LoginForm
MainButton
看到了吗?没有登录表单 "surrounding" MainButton
.
你可能想要做的是在 MainButton
和 LoginForm
的祖先中声明一个 LoginFormState
GlobalKey
,最接近的是上面我在 cursive 中标记的一个,然后将其作为构造函数参数传递给您的 LoginForm
小部件和 MainButton
。
你也可以创建一个 InheritedWidget
来包装这两个小部件并在它们中为你公开 SomeName.of()
方法,你也可以使用 provider package,这是"An InheritedWidget but for humans"(正如有人在 Flutter Europe 上所说的那样)。
在我的 LoginFormState 中我有
final signInFormKey = LabeledGlobalKey<FormState>("login_form");
static LoginFormState of(BuildContext context) {
return context.findAncestorStateOfType<LoginFormState>();
}
我的 MainButton 状态有这一行
LoginFormState.of(context)
.signInFormKey
.currentState
.validate()
并且它们都有相同的父级,它们的父级是堆栈小部件:
[
Builder( builder: (BuildContext context) => AnimatedOpacity(
opacity: status == 0 ? 0 : 1,
duration: Duration(milliseconds: 500),
child: LoginForm(),
),
),
MainButton(),
]
当我在 mainButton 状态下调用该函数时,它会记录以下错误:
发生错误是因为您在 MainButton
中调用了 LoginFormState.of()
方法,但它没有 LoginForm
祖先。
那是你的小部件树:
- 一些您在代码中没有post的小部件
Builder
AnimatedOpacity
LoginForm
MainButton
看到了吗?没有登录表单 "surrounding" MainButton
.
你可能想要做的是在 MainButton
和 LoginForm
的祖先中声明一个 LoginFormState
GlobalKey
,最接近的是上面我在 cursive 中标记的一个,然后将其作为构造函数参数传递给您的 LoginForm
小部件和 MainButton
。
你也可以创建一个 InheritedWidget
来包装这两个小部件并在它们中为你公开 SomeName.of()
方法,你也可以使用 provider package,这是"An InheritedWidget but for humans"(正如有人在 Flutter Europe 上所说的那样)。