我正试图转移到flatter_hooks,但我无法获得一些简单的textformField验证。
我有2个文本字段和一个按钮,我想在某些条件下显示错误(或者至少当文本字段为空时(
我的代码:-控制器:
final _emailFieldController =
useTextEditingController.fromValue(TextEditingValue.empty);
final _password =
useTextEditingController.fromValue(TextEditingValue.empty);
final _onSavePressed = useState(false);
-小部件:
TextFormField(
decoration: InputDecoration(hintText: "Your email"),
controller: _emailFieldController,
),
TextFormField(
obscureText: true,
onSaved: (newValue) => print(newValue),
validator: (value) =>
_onSavePressed.value && _password.text.isEmpty
? "Can't be empty"
: null,
decoration: InputDecoration(
hintText: "Password",
),
controller: _password,
),
RaisedButton(
child: Text("Create"),
onPressed: () {
_onSavePressed.value = true;
},
)
谢谢你的帮助!
使用从验证器获得的value
。例如
validator: (value) => value.isEmpty ? "Can't be empty" : null
允许您访问密码字段的值。
我在Flutter教程中就是这么做的:
class BookDetailsPage extends HookWidget {
BookDetailsPage({
Key? key,
this.bookId,
}) : super(key: key);
final int? bookId;
final _bookFormKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
final titleTextController = useTextEditingController(text: book?.title ?? '');
final authorTextController = useTextEditingController(text: book?.author ?? '');
final publishDateTextController = useTextEditingController(text: book?.publicationDate.toString() ?? '');
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(AppDimensions.l),
child: Form(
key: _bookFormKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AppTextEdit(
labelText: LocaleKeys.books_details_book_title.tr(),
textInputType: TextInputType.name,
textEditingController: titleTextController,
validator: (value) => (value == null || value.isEmpty) ? '' : null,
),
const SizedBox(height: AppDimensions.l),
AppTextEdit(
labelText: LocaleKeys.books_details_author.tr(),
textEditingController: authorTextController,
textInputType: TextInputType.name,
validator: (value) => (value == null || value.isEmpty) ? '' : null,
),
const SizedBox(height: AppDimensions.l),
AppTextEdit(
labelText: LocaleKeys.books_details_publish_date.tr(),
textInputType: TextInputType.number,
textEditingController: publishDateTextController,
validator: (value) => (value == null || value.isEmpty || int.tryParse(value) == null) ? '' : null,
),
...