Flutter: How change color of textfields if the passwords don't match?

150

You can use .addListener to the TextEditingController on initState.

A bool to change ui, you can use it to set borders color.

passwd2.addListener(() {
  setState(() {
    showError = passwd2.text.isEmpty
        ? false
        : passwd.text.trim() != passwd2.text.trim();
  });
});

you can do the same for passwd with replacing the controller and it is only needed when you also want to change ui from 1st TextFiled

// try with commenting this part
passwd.addListener(() {
  setState(() {
    showError = passwd.text.isEmpty
        ? false
        : passwd.text.trim() != passwd2.text.trim();
  });
});

And inside Column use this showError bool the way like, it can be

child: Column(
  children: <Widget>[
    //........
    if (showError) const Text("Password didnot match"),
    //.......

More about Listen to the controller for changes

Share:
150
santiagobueras
Author by

santiagobueras

Updated on January 02, 2023

Comments

  • santiagobueras
    santiagobueras over 1 year

    I'm new in flutter and I'm making a register form , I need change the color of password's textfields in real time if the passwords aren't equals, I may not be looking right, but I can't find how to do it (except one with validator: but this doesn't work in TextField).

    This is an example:

    The idea of what I want

    My code:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:fluttertoast/fluttertoast.dart';
    import 'package:http/http.dart' as http;
    import 'DashBoard.dart';
    import 'main.dart';
    import 'package:flutter/services.dart';
    //import 'package:email_validator/email_validator.dart';
    // import 'package:validators/validators.dart';
    
    class Register extends StatefulWidget {
      @override
      _RegisterState createState() => _RegisterState();
    }
    
    class _RegisterState extends State<Register> {
      TextEditingController correo = TextEditingController();
      TextEditingController celular = TextEditingController();
      TextEditingController passwd = TextEditingController();
      TextEditingController passwd2 = TextEditingController();
    
      Future register() async {
        var url =
            "http://192.168.1.139/mydatabase/register.php"; //IPv4, colocar después el hosting
        var response = await http.post(url, body: {
          "correo": correo.text,
          "celular": celular.text,
          "passwd": passwd.text,
          "passwd2": passwd2.text
        });
        var data = json.decode(response.body);
        if (data == "Error") {
          FlutterToast(context).showToast(
              child: Text(
            'User allready exit!',
            style: TextStyle(fontSize: 25, color: Colors.red),
          ));
        } else {
          FlutterToast(context).showToast(
              child: Text('Registration Successful',
                  style: TextStyle(fontSize: 25, color: Colors.green)));
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => DashBoard(),
            ),
          );
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            height: 900,
            child: Card(
              color: Colors.blue[400],
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'Register',
                      style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      decoration: InputDecoration(
                        labelText: 'Correo',
                        prefixIcon: Icon(Icons.person),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8)),
                      ),
                      controller: correo,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      maxLength: 12,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly,
                      ],
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: 'Celular',
                        prefixIcon: Icon(Icons.person),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8)),
                      ),
                      controller: celular,
                      textInputAction: TextInputAction.done,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: 'Contraseña',
                        prefixIcon: Icon(Icons.lock),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8)),
                      ),
                      controller: passwd,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: 'Password',
                        prefixIcon: Icon(Icons.lock),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8)),
                      ),
                      controller: passwd2,
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: MaterialButton(
                          color: Colors.pink,
                          child: Text('Register',
                              style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white)),
                          onPressed: () {
                            register();
                            passwd.text = "";
                          },
                        ),
                      ),
                      Expanded(
                        child: MaterialButton(
                          color: Colors.amber[100],
                          child: Text('Login',
                              style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.black)),
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => MyHomePage(),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        );
      }
    }
    

    My password's texfields have the controllers passwd and passwd2. Any suggestion? Please that you can understand it well, I'm totally beginner in flutter. Thanks.

    • Sagar Acharya
      Sagar Acharya over 2 years
      Check this out flutterforyou.com/…
    • santiagobueras
      santiagobueras over 2 years
      Sagar Acharya. thanks!!! I also wanted to change the border while I write, it was perfect!! Although I still don't understand how to do it if both passwords don't match. I think put some like this in both textfield within the "enabledBorder": validator: if [passwd.text == passwd2.text] ? [borderSide: BorderSide(color: Colors.blue, width: 2.0)] : [borderSide: BorderSide(color: Colors.red, width: 2.0)], but I don't know how make this.
    • Sagar Acharya
      Sagar Acharya over 2 years
      see first one is the actual password that you will be entering and the second one is to verification one, so in second textfield you have to check in validator that if actual password and the verification password are same. if not you have to add the red border to the second textfield.
  • santiagobueras
    santiagobueras over 2 years
    It works perfect!! Thanks so much!! (I'll share my code)