gpt4 book ai didi

flutter - FormState 与 FormFieldState,何时使用哪个?

转载 作者:行者123 更新时间:2023-12-03 04:47:40 34 4
gpt4 key购买 nike

我目前正在使用

GlobalKey<FormState> state = ...;

它完成了这项工作,我注意到还有另一个类,它是 FormFieldState ,它也有与 FormState 相同的回调,所以我也可以使用

GlobalKey<FormFieldState> state = ...;

那么,什么时候使用哪一个,谁能举个例子来演示每一个的用例?

最佳答案

假设您有一个小部件 A,其中包含一个带有 2 TextFormField 的表单。和一个按钮:

小部件A

...
Column(
children: [
Form(
child: Column(
children: [
TextFormField(...),
TextFormField(...),
]
),
),
Button(...),
]
)

现在您想要在用户按下按钮时验证表单。 GlobalKey<FormState> state在这种情况下将是你的救星,因为你可以这样做:

Column(
children: [
Form(
key: state,
child: Column(
children: [
TextFormField(...),
TextFormField(...),
]
),
),
Button(
onPressed: state.currentState.validate,
...,
),
]
)

然后想象一个TextFormField出现错误,并且您想要重置第一个 TextFormField 中的错误并将错误保留在第二个 TextFormField 中。在这种情况下,请调用 state.currentState.reset()没有帮助,因为它会重置整个表单。因此,您需要使用GlobalKey<FormFieldState> firstFormFieldState ,你可以通过以下方式解决这个问题:

Column(
children: [
Form(
key: state,
child: Column(
children: [
TextFormField(
key: firstFormFieldState,
...
),
TextFormField(...),
]
),
),
Button(
onPressed: () {
state.currentState.validate();
firstFormFieldState.reset();
},
...,
),
]
)

希望有帮助。

关于flutter - FormState 与 FormFieldState,何时使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003066/

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