如何在flutter中使按钮处于非活动状态,直到正确填写了必填字段

dojqjjoe  于 2023-01-18  发布在  Flutter
关注(0)|答案(4)|浏览(120)

我想使一个特定的按钮不活动,并在所有的必填字段填写正确之前使用不同的颜色,我还希望在文本字段下有一条消息,告诉用户正确填写字段,如果他们没有。这是我目前所拥有的:[![这是我目前拥有的][1]][1]
但我想要这样的东西:
下面是我的代码:

TextField(
                  // controller:
                  obscureText: false,
                  maxLines: null,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    labelText: "Email Address",
                    labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
                    floatingLabelStyle:
                        TextStyle(color: Colors.black, fontSize: 20),
                    hintText: 'Email Address',
                    hintStyle: TextStyle(fontSize: 0.5),
                    isDense: true,
                    enabledBorder: OutlineInputBorder(
                      borderSide:
                          const BorderSide(width: 2.0, color: Colors.grey),
                      borderRadius: BorderRadius.circular(7),
                    ),
                    focusedBorder: OutlineInputBorder(
                        borderSide:
                            const BorderSide(color: Colors.green, width: 2.0),
                        borderRadius: BorderRadius.circular(7)),
                  ),
                  onChanged: (value) {
                    setState(() {
                      _email = value.trim();
                    });
                  },
                ),

这是我的按钮代码:

GestureDetector(
                  onTap: (() {}),
                  child: Container(
                    child: Center(
                      child: Padding(
                        padding: const EdgeInsets.all(20),
                        child: Text(
                          "Continue",
                          style: TextStyle(fontSize: 19, color: Colors.white),
                        ),
                      ),
                    ),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        color: Colors.green),
                  ),
                ),
ldioqlga

ldioqlga1#

创建状态bool以控制onPressed活动模式,并侦听TextFiled上的更改并更新bool。

late final TextEditingController controller = TextEditingController()
    ..addListener(() {
      // your logic
      if (controller.text == "asd") {
        isValid = true;
      } else {
        isValid = false;
      }

      setState(() {});
    });

  bool isValid = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextFormField(
            controller: controller,
          ),
          ElevatedButton(
              onPressed: isValid
                  ? () {
//your operation
                    }
                  : null,
              child: Text("login")),
        ],
      ),
    );
  }
}
w6mmgewl

w6mmgewl2#

添加一个bool类型变量......并检查textfield值是否有效,如示例bool值是否为真,buttoncolors是否可更改和单击

TextField(
  // controller:
  obscureText: false,
  maxLines: null,
  keyboardType: TextInputType.emailAddress,
  decoration: InputDecoration(
    border: const OutlineInputBorder(),
    labelText: "Email Address",
    labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
    floatingLabelStyle:
    TextStyle(color: Colors.black, fontSize: 20),
    hintText: 'Email Address',
    hintStyle: TextStyle(fontSize: 0.5),
    isDense: true,
    enabledBorder: OutlineInputBorder(
      borderSide:
      const BorderSide(width: 2.0, color: Colors.grey),
      borderRadius: BorderRadius.circular(7),
    ),
    focusedBorder: OutlineInputBorder(
        borderSide:
        const BorderSide(color: Colors.green, width: 2.0),
        borderRadius: BorderRadius.circular(7)),
  ),
  onChanged: (value) {
    if(value.length>6) {
      setState(() {
        enableButton = true;
      });
    }else {
      setState(() {
        enableButton = false;
      });
    }
  },
),
GestureDetector(
  onTap: (() {
    if(enableButton){
      //do what you want
    }
  }),
  child: Container(
    child: Center(
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Text(
          "Continue",
          style: TextStyle(fontSize: 19, color: Colors.white),
        ),
      ),
    ),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(50),
        color: enableButton ? Colors.green : Colors.grey
    ),
  ),
),
kulphzqa

kulphzqa3#

检查此工作是否正常

final emailController = TextEditingController();

  // email text field
   TextFormField(
                  controller: emailController,
                  decoration: InputDecoration(
                    labelText: "Name",
                    labelStyle: TextStyle(
                      color: Colors.lightGreen
                    ),
                    errorStyle: TextStyle(
                      color: Colors.black
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5.0)
                    )
                  ),
                  validator: (value){
                    if(value == null || value == ''){
                      return "Enter name";
                    }
                  },
                ) 


// button
           GestureDetector(
              onTap: (() {
                if (emailController.text.toString().isNotEmpty) {
                  //todo
                } else {
                  print("please enter email");
                }
              }),
              child: Container(
                child: Center(
                  child: Padding(
                    padding: const EdgeInsets.all(20),
                    child: Text(
                      "Continue",
                      style: TextStyle(fontSize: 19, color:emailController.text.toString().isNotEmpty? Colors.green: Colors.grey),
                    ),
                  ),
                ),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(50),
                    color: Colors.green),
              ),
            ),
oymdgrw7

oymdgrw74#

使用Form验证字段。当其中一个字段更改时,将调用onChanged,因此请在此处设置状态。只要表单无效,就通过将onPressed设置为null来禁用按钮。对TextFormField使用AutovalidateMode.always可启用验证,而无需用户交互。

class MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();
  bool _isValid = false;

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      onChanged: () {
        setState(() => _isValid = _formKey.currentState!.validate());
      },
      child: Column(
        children: [
          TextFormField(
            autofocus: true,
            autovalidateMode: AutovalidateMode.always,
            validator: (value) => (value == null || value.isEmpty)
                ? 'Error'
                : null,
          ),
          ElevatedButton(
            onPressed: _isValid ? () {} : null,
            child: const Text('Submit'),
          ),
        ],
      ),
    );
  }
}

相关问题