【问题标题】:Flutter Set circular progress indicator to false in TextFormField validatorFlutter 在 TextFormField 验证器中将循环进度指示器设置为 false
【发布时间】:2025-12-03 00:25:01
【问题描述】:

我有一个登录屏幕,在该屏幕中有两个字段,一个用于电子邮件,另一个用于密码。这两个文本字段都有一个验证器,验证是文本字段是空还是空。下面我有一个提交按钮,我的问题是,如果文本字段在这种情况下不验证,如果文本字段为 null 或其中之一,我如何使 loading = false。

global variable >>> bool loading = false;


TextFormField loginEmailTextField() {
    return TextFormField(
      enableInteractiveSelection: false,
      keyboardType: TextInputType.number,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please enter your phone number';
        }
        return null;
      },
      controller: emailController,
      onChanged: (value) {
        setState(() {});
      },
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.phone),
        suffixIcon: emailController.text.isEmpty
            ? const Text('')
            : GestureDetector(
                onTap: () {
                  emailController.clear();
                },
                child: const Icon(Icons.close),
              ),
        labelText: 'Phone',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.red, width: 1),
        ),
      ),
    );
  }

  TextFormField loginPasswordTextField() {
    return TextFormField(
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please enter your password';
        }
        return null;
      },
      obscureText: isVisible,
      controller: passwordController,
      onChanged: (value) {
        print(value);
      },
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.lock),
        suffixIcon: GestureDetector(
          onTap: () {
            isVisible = !isVisible;
            setState(() {});
          },
          child: Icon(isVisible ? Icons.visibility : Icons.visibility_off),
        ),
        labelText: 'Password',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.red, width: 1),
        ),
      ),
    );
  }

  Column loginSubmitButton(double width, double height, BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          width: width / 2,
          height: height / 12,
          child: ElevatedButton(
            onPressed: () async {
              if (_formKey.currentState!.validate()) {
                Future<Response> futureResponse = fetchWorkingLocationData();
                futureResponse
                    .then((response) => {
                          if (response.statusCode == 200)
                            {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => MenuPage()),
                              )
                            }
                          else
                            {
                              setState(() {
                                loading = false;
                              }),
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  backgroundColor: Colors.blue,
                                  content: Text(
                                    "Incorrect phone number or password",
                                    style: TextStyle(fontSize: 18),
                                  ),
                                  duration: Duration(seconds: 4),
                                ),
                              ),
                            },
                        })
                    .catchError((error, stackTrace) => print('shush'));
              }
              if (loading) return;
              setState(() {
                loading = true;
              });
            },
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              child: loading
                  ? Loading()
                  : Text(
                      'Submit',
                      style: TextStyle(fontSize: 22, color: Colors.white),
                    ),
            ),
            style: ButtonStyle(
              shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies


    【解决方案1】:

    首先您按下按钮,您将检查凭据是否为空白/Null,如果不是,则继续下一步, 然后加载变量为真,并执行api进程,响应加载变量为假后。

    【讨论】:

    • 我不认为我理解你的解释,我想要现在的代码,只有当变量是空的 loading = false;
    【解决方案2】:

    像这样

    Future<String> signIn() async {
        if (IDforlogin.text != '') {
          if (password.text != '') {
            setState(() {
              _isloading = true;
            });
            Map data = {
              'email': IDforlogin.text.trim(),
              'password': password.text.trim(),
              'fcm_token': fcm_token.toString()
            };
            print(data);
            var response = await http.post(API_URL + 'login', body: data);
            try {
              print(response.body);
              var decodedData = json.decode(response.body);
              print(decodedData['code']);
              if (decodedData['code'] == 200) {
                setState(() {
                  _isloading = false;
                });
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => dashbord()),
                );
              } else {
                setState(() {
                  _isloading = false;
                });
                Toast.show(decodedData['message'], context,
                    duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
              }
            } catch (error) {
              setState(() {
                _isloading = false;
              });
              Toast.show(errormessage, context,
                  duration: Toast.LENGTH_LONG,
                  gravity: Toast
                      .CENTER); // executed for errors of all types other than Exception
            }
          } else {
            Toast.show('Please enter password', context,
                duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
          }
        } else {
          Toast.show('Please enter ID', context,
              duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
        }}
    

    【讨论】:

      【解决方案3】:

      我找到了一个符合我个人需要的答案

      TextFormField loginEmailTextField() {
          return TextFormField(
            enableInteractiveSelection: false,
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your phone number';
              }
              return null;
            },
            controller: emailController,
            onChanged: (value) {
              setState(() {});
            },
            decoration: InputDecoration(
              prefixIcon: const Icon(Icons.phone),
              suffixIcon: emailController.text.isEmpty
                  ? const Text('')
                  : GestureDetector(
                      onTap: () {
                        emailController.clear();
                      },
                      child: const Icon(Icons.close),
                    ),
              labelText: 'Phone',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Colors.red, width: 1),
              ),
            ),
          );
        }
      
        TextFormField loginPasswordTextField() {
          return TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your password';
              }
              return null;
            },
            obscureText: isVisible,
            controller: passwordController,
            onChanged: (value) {
              print(value);
            },
            decoration: InputDecoration(
              prefixIcon: const Icon(Icons.lock),
              suffixIcon: GestureDetector(
                onTap: () {
                  isVisible = !isVisible;
                  setState(() {});
                },
                child: Icon(isVisible ? Icons.visibility : Icons.visibility_off),
              ),
              labelText: 'Password',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Colors.red, width: 1),
              ),
            ),
          );
        }
      
        Column loginSubmitButton(double width, double height, BuildContext context) {
          return Column(
            children: <Widget>[
              Container(
                width: width / 2,
                height: height / 12,
                child: ElevatedButton(
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      setState(() {
                        loading = true;
                      });
                      Future<Response> futureResponse = fetchWorkingLocationData();
                      futureResponse
                          .then((response) => {
                                if (response.statusCode == 200)
                                  {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => MenuPage()),
                                    )
                                  }
                                else
                                  {
                                    setState(() {
                                      try {
                                        loading = false;
                                      } on Exception catch (e, s) {
                                        loading = true;
                                      }
                                    }),
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        backgroundColor: Colors.blue,
                                        content: Text(
                                          "Incorrect phone number or password",
                                          style: TextStyle(fontSize: 18),
                                        ),
                                        duration: Duration(seconds: 4),
                                      ),
                                    ),
                                  },
                              })
                          .catchError((error, stackTrace) => print('shush'));
                    }
                  },
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    child: loading
                        ? Loading()
                        : Text(
                            'Submit',
      

      【讨论】: