skip to Main Content

I am trying to change the colour of a Text field widget to red if the email address does not exist or is incorrect. This change should happen as soon as the login button is clicked:

Here is the code where I would like the border colour of the TextFormField Widget to turn red if the isError variable is set to false:

code for the widget that needs the borders to turn red:

alignment: AlignmentDirectional(0.00, -0.60),

                child: Form( 
                  key: _formKey,
                  child:Padding(
                  padding: EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0),
                  child: Container(
                    width: 320,
                    child: TextFormField(
                      autofocus: true,
                      autofillHints: [AutofillHints.email],
                      textCapitalization: TextCapitalization.none,
                      textInputAction: TextInputAction.next,
                      obscureText: false,
                      decoration: InputDecoration(
                        labelText: 'Type your Email Address ',
                        labelStyle:
                            TextStyle(
                                  fontFamily: 'Readex Pro',
                                  color: Color(0xFF7B7B7B),
                                  fontWeight: FontWeight.normal,
                                ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.white,
                            width: 3,
                          ),
                          borderRadius: BorderRadius.circular(5),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.white,
                            width: 3,
                          ),
                          borderRadius: BorderRadius.circular(5),
                        ),
                        errorBorder: 
                          isError
                          ?UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.red,
                            width: 30,
                          ),
                          borderRadius: BorderRadius.circular(50),
                          

                        ):
                        UnderlineInputBorder(
                        borderSide: BorderSide(
                        color: Color.fromARGB(255, 255, 255, 255),
                        width: 3,
                        ),
                        borderRadius: BorderRadius.circular(5),
                        ),
                        prefixIcon: Icon(
                          Icons.email_outlined,
                          color: Colors.white,
                          size: 25,
                        ),
                      ),
                      style: TextStyle(
                            fontFamily: 'Readex Pro',
                            color: Colors.white,
                          ),
                      keyboardType: TextInputType.emailAddress,
                      
                      
                      onChanged: (value) {
                      setState(() {
                      email = value; 
                      });
                      },
                     

                   
                      
                    ),
                  ),
                ),
              ),),

Here is the code where the isError variable is set:

class _Login_pageState extends State<Login_page> {
  bool isError = false;
  String email = ""; // Variable to store email
  String password = ""; // Variable to store password
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();



  @override
  Widget build(BuildContext context) {



Future<String> loginAPI(String username, String password) async {
  var client = http.Client();
  try {
    var apiUrl = Uri.parse('http://127.0.0.1:8000/login_request?username=$username&password=$password');

    var response = await client.get(apiUrl);
    return response.body;
  } finally {
    client.close();
  }
}




var main_stack= Stack(children: [
    

                  
                  
                  
                  
              Align(
                alignment: AlignmentDirectional(0.00, -0.1),
                child: TextButton(
                  onPressed: () async {
                    if (_formKey.currentState != null && _formKey.currentState!.validate()) {
                      String apiResponse = await loginAPI(email, password);
                      print(apiResponse);
                      if (apiResponse == 'false') {
                       setState(() {
                        isError = true; 
                      });
                      } 
                    }
                  },

I would like the border of the text field widget to turn red as soon as the API returns false.

2

Answers


  1. Flutter will not detect errorBorder until error is triggered by text field it self by using TextFormField and validator method you can achive this behaviour.

    For normal text fields you need to set your FocusBorder and EnabledBorder with red color and instead of changing border widget it self you can just toggle the colors with red or white (whatever your normal border color is)

    Login or Signup to reply.
  2. @Zak345 After looking at your code, to achieve what you want, please refer to the following code. If you want to display an error when the button is clicked, you need to add a validator.

    class MyCustomFormState extends State<MyCustomForm> {
    
      final _formKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
        // Build a Form widget using the _formKey created above.
        return Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                // The validator receives the text that the user has entered.
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                },
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 16),
                child: ElevatedButton(
                  onPressed: () {
                    // Validate returns true if the form is valid, or false otherwise.
                    if (_formKey.currentState!.validate()) {
                      // 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(
                        const SnackBar(content: Text('Processing Data')),
                      );
                    }
                  },
                  child: const Text('Submit'),
                ),
              ),
            ],
          ),
        );
      }
    }
    

    I hope this is helpful!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search