如何在 Flutter 文本表单字段具有有效数据之前禁用按钮

How to disable button until Flutter text form field has valid data

我想在文本表单字段有效之前禁用按钮。然后,一旦数据有效,就应该启用该按钮。我之前收到过关于 SO 的类似问题的帮助,但似乎无法将我学到的知识应用到这个问题上。当用户添加超过 3 个字符且少于 20 个字符时,数据有效。我创建了一个 bool (_isValidated),并在用户输入有效数据后将其添加到调用 setState 的 validateUserName 方法中,但这绝对是错误的并会生成一条错误消息.错误信息是:

在构建过程中调用了 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,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

我认为更好的方法是给按钮的onPressed参数赋一个空值。请检查以下 link。 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!!!"),
            ),
          ),
        ],
      ),
    );
  }

只需使用表单验证,在 TextFormField 编辑验证器函数中,添加 onChange 函数并调用 setState 来获取 inputtedValue,它也可以保留禁用按钮,除非表单被验证。

注意要点:

  1. 使用final _formKey = GlobalKey<FormState>();
  2. String? inputtedValue;!userInteracts()是技巧,可以参考代码;
  3. 当ElevatedButton的onPressed方法为null时,按钮将被禁用。只要传递条件 !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'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}