Flutter文本字段验证

huangapple go评论60阅读模式
英文:

Flutter textformfileds validation

问题

以下是您的代码的中文翻译部分:

在我的代码中,我正在使用验证器来验证文本字段中的内容,目前一切都正常。现在我想要的是,如果用户没有输入任何内容,只是按下回车按钮,我希望将位于hinttext中的数据发送到服务器。如果提示文本不包含任何数据,且用户按下按钮,我想要进行验证。

Textfields( 
 hintText: data.data.firstName == null ? '名字' : data.data.firstName,
 validator: validateNames,
 onChanged: (String value) {
   firstName = value; 
 },
 onSaved: (input) => firstName = input,
 autofocus: true,
 prefixIcon: const Icon(Icons.person),
),

这是我的按钮

BlocBuilder<BasicInfoCubit, BasicInfoState>(
  builder: (context, state) {
    return Align(
      alignment: Alignment.centerRight,
      child: CustomButton(
        horizontal: kDefaultSpacing,
        width: size.width / 2.5,
        title: '继续',
        isDisabled: false,
        loading: state.maybeWhen(
          orElse: () => false,
          loading: () => true,
        ),
        onPressed: () async {
          final isValid = _formKey.currentState?.validate();
          if (!isValid!) {
            return;
          } else {
            await context.read<BasicInfoCubit>().basicInfo(
              firstName: firstName == null
                ? data.data.firstName.toString()
                : firstName.toString(),
            );
            Future.delayed(
              const Duration(seconds: 1),
            );
          }
        },
      ),
    );
  },
),

请注意,代码中的一些文本是硬编码的,您可以根据需要将其本地化为您的应用程序语言。

英文:

In my code I am using validator to validate in texformfields and it is working fine, and now what I want is if user doesn't type anything and just presses enter button I want the data which is in hinttext to be sent to server and if hint text doesn't any contain data and if user presses button then I want validation texts.

 Textfields( 
 hintText: data.data.firstName == null ? &#39;First Name&#39; : data.data.firstName,
 validator: validateNames,
 onChanged: (String value) {
 firstName = value; },
 onSaved: (input) =&gt; firstName = input,
 autofocus: true,
 prefixIcon: const Icon(Icons.person),
 ),

This is my button

 BlocBuilder&lt;BasicInfoCubit, BasicInfoState&gt;(
                        builder: (context, state) {
                          return Align(
                            alignment: Alignment.centerRight,
                            child: CustomButton(
                              horizontal: kDefaultSpacing,
                              width: size.width / 2.5,
                              title: &#39;Continue &#39;,
                              isDisabled: false,
                              loading: state.maybeWhen(
                                orElse: () =&gt; false,
                                loading: () =&gt; true,
                              ),
                              onPressed: () async {
                                final isValid =
                                    _formKey.currentState?.validate();
                                if (!isValid!) {
                                  return;
                                } else {
                                  await context
                                      .read&lt;BasicInfoCubit&gt;()
                                      .basicInfo(
                                        firstName: firstName == null
                                            ? data.data.firstName.toString()
                                            : firstName.toString(),
                                   
                                      );
                                  Future.delayed(
                                    const Duration(seconds: 1),
                                  );
                                }
                              },
                            ),
                          );
                        },
                      ),

答案1

得分: 1

可以使用一个变量来保存提示,并在提交时使用相同的提示值。

```dart
import 'package:flutter/material.dart';

void main() => runApp(const SignUpApp());

class SignUpApp extends StatelessWidget {
  const SignUpApp();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/': (context) => const SignUpScreen(),
      },
    );
  }
}

class SignUpScreen extends StatelessWidget {
  const SignUpScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: const Center(
        child: SizedBox(
          width: 400,
          child: Card(
            child: SignUpForm(),
          ),
        ),
      ),
    );
  }
}

class SignUpForm extends StatefulWidget {
  const SignUpForm({super.key});

  @override
  State<SignUpForm> createState() => _SignUpFormState();
}

class _SignUpFormState extends State<SignUpForm> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  static const String _firstNameHint = '名字';
  late TextEditingController _firstNameTextController;
  late TextEditingController _lastNameTextController;

  @override
  void initState() {
    _firstNameTextController = TextEditingController();
    _lastNameTextController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _firstNameTextController.dispose();
    _lastNameTextController.dispose();
    super.dispose();
  }

  _submit() {
    if (_formKey.currentState != null && _formKey.currentState!.validate()) {}
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextFormField(
              controller: _firstNameTextController,
              decoration: const InputDecoration(
                hintText: _firstNameHint,
              ),
              textInputAction: TextInputAction.next,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  if (_firstNameHint.isNotEmpty) {
                    _firstNameTextController.text = _firstNameHint;
                    return null;
                  }
                  return '名字不能为空';
                }
                return null;
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextFormField(
              controller: _lastNameTextController,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              textInputAction: TextInputAction.next,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '姓氏不能为空';
                }
                return null;
              },
            ),
          ),
          TextButton(
            onPressed: () {
              _submit();
            },
            child: const Text('注册'),
          ),
        ],
      ),
    );
  }
}

您还可以创建一个自定义的TextFormField来执行上述操作。


<details>
<summary>英文:</summary>
You can use a variable holding the hint and use the same hint&#39;s value while submitting.

import 'package:flutter/material.dart';

void main() => runApp(const SignUpApp());

class SignUpApp extends StatelessWidget {
const SignUpApp();

@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => const SignUpScreen(),
},
);
}
}

class SignUpScreen extends StatelessWidget {
const SignUpScreen({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: const Center(
child: SizedBox(
width: 400,
child: Card(
child: SignUpForm(),
),
),
),
);
}
}

class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});

@override
State<SignUpForm> createState() => _SignUpFormState();
}

class _SignUpFormState extends State<SignUpForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
static const String _firstNameHint = 'First name';
late TextEditingController _firstNameTextController;
late TextEditingController _lastNameTextController;

@override
void initState() {
_firstNameTextController = TextEditingController();
_lastNameTextController = TextEditingController();
super.initState();
}

@override
void dispose() {
_firstNameTextController.dispose();
_lastNameTextController.dispose();
super.dispose();
}

_submit() {
if (_formKey.currentState != null && _formKey.currentState!.validate()) {}
}

@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _firstNameTextController,
decoration: const InputDecoration(
hintText: _firstNameHint,
),
textInputAction: TextInputAction.next,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null || value.isEmpty) {
if (_firstNameHint.isNotEmpty) {
_firstNameTextController.text = _firstNameHint;
return null;
}
return 'First name is required';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _lastNameTextController,
autovalidateMode: AutovalidateMode.onUserInteraction,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Last name is required';
}
return null;
},
),
),
TextButton(
onPressed: () {
_submit();
},
child: const Text('Sign up'),
),
],
),
);
}
}


You can also create a Custom TextFormField which will do all of the above.
</details>

huangapple
  • 本文由 发表于 2023年4月17日 18:25:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定