gpt4 book ai didi

mobile - Flutter:根据验证更改状态

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

我正在为一个演示应用构建一个简单的忘记密码表单,该表单由一个 TextFormFields 和一个用于提交数据的 FloatingActionButton 组成。我已经意识到 FloatingActionButton 没有这样的禁用 bool 状态,所以我想尝试通过将状态更改为 _isValid: true/false 来复制它,具体取决于TextFormField 验证函数,然后我可以将一些三元运算符放在 FloatingActionButton 上以根据此小部件的状态更改颜色和功能。

您将能够看到我在安装小部件时将 _autoValidate 设置为 true,然后我尝试在 _validateForgetEmail 函数中触发 UI 重新加载。当我触发这些状态更改时,我会收到一个很大的 UI 错误提示

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building Form-[LabeledGlobalKey<FormState>#0a40e](dirty, state:
flutter: FormState#59216):
flutter: setState() or markNeedsBuild() called during build.
flutter: This ForgotPasswordForm widget cannot be marked as needing to build because the framework is already
flutter: in the process of building widgets. A widget can be marked as needing to be built during the build
flutter: phase only if one of its ancestors is currently building. This exception is allowed because the
flutter: framework builds parent widgets before children, which means a dirty descendant will always be
flutter: built. Otherwise, the framework might not visit this widget during this build phase.

代码如下:

class ForgotPasswordForm extends StatefulWidget {
@override
_ForgotPasswordFormState createState() => _ForgotPasswordFormState();
}
Class _ForgotPasswordFormState extends State<ForgotPasswordForm> {
final _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
final bool _autoValidate = true;

bool _isLoading = false;
bool _isValid = false;

String email;

@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: _isLoading
? _buildLoadingSpinner(context)
: _buildPasswordForm(context),
autovalidate: _autoValidate,
);
}

Widget _buildLoadingSpinner(BuildContext context) {
return (Center(child: CircularProgressIndicator()));
}

Widget _buildPasswordForm(BuildContext context) {
print('isValid: ' + _isValid.toString());

return Column(
children: <Widget>[
Text(
'Please enter your email address.',
style: TextStyle(fontSize: 14.0),
textAlign: TextAlign.center,
),
Text(
'You will recieve a link to reset your password.',
style: TextStyle(fontSize: 14.0),
textAlign: TextAlign.center,
),
SizedBox(height: 32.0),
TextFormField(
controller: _emailController,
validator: _validateForgetEmail,
keyboardType: TextInputType.emailAddress,
autovalidate: _autoValidate,
style: TextStyle(fontSize: 14.0),
onSaved: (String val) {
email = val;
},
decoration: InputDecoration(
filled: true,
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
labelText: 'Email',
border: InputBorder.none,
labelStyle: TextStyle(fontSize: 14.0, color: Colors.lightBlueAccent),
errorStyle: TextStyle(fontSize: 10.0, height: 0.5),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.lightGreenAccent, width: 2.0),
),
),
),
SizedBox(height: 24.0),
FloatingActionButton(
backgroundColor: _isValid ? Colors.lightBlue : Colors.grey,
onPressed: () {
_submitPasswordReset();
},
child: Icon(Icons.arrow_forward_ios, size: 14.0),
)
],
mainAxisAlignment: MainAxisAlignment.center,
);
}

void _submitPasswordReset() async {
if (_formKey.currentState.validate()) {
setState(() {
_isLoading = true;
});

UserPasswordResetRequest newPasswordRequest =
new UserPasswordResetRequest(email: _emailController.text);

http.Response response = await ApiService.queryPost(
'/api/users/password-forgot',
body: newPasswordRequest.toJson());

final int statusCode = response.statusCode;

if (statusCode == 400) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Wrong email or password'),
duration: Duration(seconds: 3),
backgroundColor: Colors.red));

setState(() {
_isLoading = false;
});
}

if (statusCode == 200) {
// setState(() {
// _isLoading = false;
// });

Navigator.push(
context,
MaterialPageRoute(builder: (context) => UserBackToLogin()),
);
}

setState(() {
_isLoading = false;
});
}
}

String _validateForgetEmail(String value) {
String patttern =
r"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$";
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Email is Required";
} else if (!regExp.hasMatch(value)) {
setState(() {
_isValid = false;
});

return "Must be a valid email address";
}

print('value' + value);

setState(() {
_isValid = true;
});

return null;
}
}

任何洞察力都会很高兴看到我做错了什么 - flutter 非常新。如果您需要更多信息,我可以提供。

山姆干杯

最佳答案

你可以这样做:
_validateForgetEmail 方法一分为二:

String _validateForgetEmail(String value) {
if (value.length == 0) {
return "Email is Required";
} else if (!_isEmailValid(value)) {
return "Must be a valid email address";
}

print('value' + value);

return null;
}

bool _isEmailValid(String value) {
String pattern =
r"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$";
RegExp regExp = new RegExp(pattern);

return regExp.hasMatch(value);
}

现在这些方法只验证值而不影响任何状态。

监听 _emailController 变化

@override
void initState() {
super.initState();
_emailController.addListener(() {
final isEmailValid = _isEmailValid(_emailController.value.text);
if(isEmailValid != _isValid) {
setState(() {
_isValid = isEmailValid;
});
}
});
}

也不要忘记处理 _emailController

@override
void dispose() {
_emailController.dispose();
super.dispose();
}

异常说明:
TextFormField 扩展了 FormField 类。如果 autovalidate 开启,则作为 validator 传递的函数将在 FormFieldState.build 方法中调用以更新错误文本。
所以它导致 setStatebuild 调用,这是框架不允许的

关于mobile - Flutter:根据验证更改状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57141105/

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