gpt4 book ai didi

dart - 文本表单字段 : setState() or markNeedsBuild() called during build

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

我试图将第一次按钮设置为禁用,当用户输入数量时它被启用,按钮禁用工作正常但是当我在 TextFormField 中输入数量时它给出以下错误。

   I/flutter (29519): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY 
╞═══════════════════════════════════════════════════════════
I/flutter (29519): The following assertion was thrown building
TextFormField(dirty, state: _TextFormFieldState#b89da):
I/flutter (29519): setState() or markNeedsBuild() called during build.
I/flutter (29519): This HomePage widget cannot be marked as needing to
build because the framework is already in the
I/flutter (29519): process of building widgets. A widget can be marked as
needing to be built during the build phase
I/flutter (29519): only if one of its ancestors is currently building.
This exception is allowed because the framework
I/flutter (29519): builds parent widgets before children, which means a
dirty descendant will always be built.
I/flutter (29519): Otherwise, the framework might not visit this widget
during this build phase.
I/flutter (29519): The widget on which setState() or markNeedsBuild() was
called was:

我的代码:

var _onPressed;
if (isButtonDisabled) {
_onPressed = () {
print("Hello");
};
}

TextFormField代码:

child: TextFormField(
decoration: InputDecoration(
contentPadding: EdgeInsets.only(
left: 12.0,
right: 12.0,
top: 12.0,
bottom: 12.0
),
labelText: 'Enter amount',
hintText: 'Enter amount',
hintStyle: TextStyle(
color: Colors.red,
fontSize: 14.0
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(0.0)
),
),
keyboardType: TextInputType.number,
autovalidate: true,
validator: (String txt) {
if (txt.length == 2) {
setState(() {
isButtonDisabled = true;
});
} else {
setState(() {
isButtonDisabled = false;
});
}
}
),

按钮代码:

FlatButton(
child: Text("Confirm"),
onPressed: _onPressed,
)

最佳答案

中移除 setState
   if (txt.length == 2){
setState((){
isButtonDisabled = true;
});
} else {
setState((){
isButtonDisabled = false;
});
}}),

   if (txt.length == 2){
isButtonDisabled = true;
} else {
isButtonDisabled = false;
}}),

你不需要在直接在build()中执行的代码中调用setState(),只有当你传递像

这样的函数时
onPressed: () {
// code here is not executed in `build()`,
it's just passed to `onPressed` to be executed when the button is tapped
// therefore here `setState()` is required for state changes
}

validator: () {...} 看起来很相似,但不会更新您的小部件的状态。

关于dart - 文本表单字段 : setState() or markNeedsBuild() called during build,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54005601/

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