簡體   English   中英

Flutter 在 TextFormField 驗證器中將循環進度指示器設置為 false

[英]Flutter Set circular progress indicator to false in TextFormField validator

我有一個登錄屏幕,在該屏幕中有兩個字段,1 個用於 email,另一個用於密碼。 這兩個文本字段都有一個驗證器,驗證是文本字段是 null 還是空。 下面我有一個提交按鈕,我的問題是如果文本字段在這種情況下沒有驗證,如果文本字段是 null 或其中之一,我如何使加載 = 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),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

首先按下按鈕,您將檢查憑據是否為空白/Null,如果不是,則繼續下一步,然后加載變量您可以為 true,並執行 api 過程,在響應加載變量 false 之后。

像這樣

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);
    }}

我找到了一個適合我需要的答案

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',

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM