我想禁用按钮,直到文本表单字段有效。一旦数据有效,按钮就应该被启用。我之前收到过有关类似问题的帮助,但似乎无法将我学到的知识应用于这个问题。当用户添加超过 3 个字符且少于 20 个字符时,数据有效。我创建了一个 bool (_isValidated) 并将其添加到 validateUserName 方法中,一旦用户输入了有效数据,调用 setState 但这绝对是错误的并生成错误消息。错误信息是:
在构建期间调用 setState() 或 markNeedsBuild()。
我不知道我做错了什么。任何帮助,将不胜感激。谢谢你。
class CreateUserNamePage extends StatefulWidget {
const CreateUserNamePage({
Key? key,
}) : super(key: key);
@override
_CreateUserNamePageState createState() => _CreateUserNamePageState();
}
class _CreateUserNamePageState extends State<CreateUserNamePage> {
final _formKey = GlobalKey<FormState>();
bool _isValidated = false;
late String userName;
final TextEditingController _userNameController = TextEditingController();
@override
void initState() {
super.initState();
_userNameController.addListener(() {
setState(() {});
});
}
void _clearUserNameTextField() {
setState(() {
_userNameController.clear();
});
}
String? _validateUserName(value) {
if (value!.isEmpty) {
return ValidatorString.userNameRequired;
} else if (value.trim().length < 3) {
return ValidatorString.userNameTooShort;
} else if (value.trim().length > 20) {
return ValidatorString.userNameTooLong;
} else {
setState(() {
_isValidated = true;
});
return null;
}
}
void _createNewUserName() {
final form = _formKey.currentState;
if (form!.validate()) {
form.save();
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Welcome $userName'),
),
);
Timer(const Duration(seconds: 2), () {
Navigator.pop(context, userName);
});
}
@override
void dispose() {
_userNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final isPortrait =
MediaQuery.of(context).orientation == Orientation.portrait;
final screenHeight = MediaQuery.of(context).size.height;
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
appBar: CreateUserNameAppBar(
preferredAppBarSize:
isPortrait ? screenHeight / 15.07 : screenHeight / 6.96,
),
body: ListView(
children: [
Column(
children: [
const CreateUserNamePageHeading(),
CreateUserNameTextFieldTwo(
userNameController: _userNameController,
createUserFormKey: _formKey,
onSaved: (value) => userName = value as String,
suffixIcon: _userNameController.text.isEmpty
? const EmptyContainer()
: ClearTextFieldIconButton(
onPressed: _clearUserNameTextField,
),
validator: _validateUserName,
),
CreateUserNameButton(
buttonText: ButtonString.createUserName,
onPressed: _isValidated ? _createNewUserName : null,
),
],
),
],
),
),
);
}
}
简单地使用表单验证,在
TextFormField
编辑验证器函数中,添加onChange函数并调用setState
来获取inputtedValue,除非表单经过验证,否则也可以保持禁用按钮。
注意要点:
final _formKey = GlobalKey<FormState>();
String? inputtedValue;
和!userInteracts()
是技巧,可以参考代码;!userInteracts() || _formKey.currentState == null || !_formKey.currentState!.validate()
代码在这里:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyCustomForm(),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({Key? key}) : super(key: key);
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
// recording fieldInput
String? inputtedValue;
// you can add more fields if needed
bool userInteracts() => inputtedValue != null;
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Scaffold(
appBar: AppBar(
title: const Text('Form Disable Button Demo'),
),
body: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
if (inputtedValue != null && (value == null || value.isEmpty)) {
return 'Please enter some text';
}
return null;
},
onChanged: (value) => setState(() => inputtedValue = value),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
// return null will disable the button
// Validate returns true if the form is valid, or false otherwise.
onPressed: !userInteracts() || _formKey.currentState == null || !_formKey.currentState!.validate() ? null :() {
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Processing Data: ' + inputtedValue!)),
);
},
child: const Text('Submit'),
),
),
],
),
),
);
}
}
我认为更好的方法是为按钮的 onPressed 参数分配一个 null 值。请检查以下链接。 https://www.flutterbeads.com/disable-button-in-flutter/
您有自定义小部件,所以我不知道您的小部件是如何工作的,但在这里您可以使用 AbsorbPointer 禁用按钮并检查 onChange 参数中的 textformfield 文本,如下所示;
bool isDisabled = true;
String _validateUserName(value) {
if (value!.isEmpty) {
return ValidatorString.userNameRequired;
} else if (value.trim().length < 3) {
return ValidatorString.userNameTooShort;
} else if (value.trim().length > 20) {
return ValidatorString.userNameTooLong;
} else {
setState(() {
isDisabled = false;
});
return null;
}
}
@override
Widget build(BuildContext context) {
final ButtonStyle style =
ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ElevatedButton(
style: style,
onPressed: null,
child: const Text('Disabled'),
),
const SizedBox(height: 30),
TextFormField(
decoration: const InputDecoration(
labelText: 'Label',
),
onChanged: (String value) {
_validateUserName(value);
},
),
AbsorbPointer(
absorbing: isDisabled, // by default is true
child: TextButton(
onPressed: () {},
child: Text("Button Click!!!"),
),
),
],
),
);
}
禁用按钮的方法始终是将 null 传递给 onPressed 回调,您可以使用按钮主题设置它们的样式。然而,在像下面这样构建小部件树时尝试调用 validate() 会抛出错误
ProgressButton(
isLoading: isLoading,
onPressed: _formKey.currentState?.validate() == true ? () {
// saveEvent();
} : null,
label: isEditing ? 'Save' : 'Create',
),
更好的方法是在流中的某个位置保存一个布尔值并更新它