Flutter TextFormField validation with Firestore

31 views Asked by At

I have created a TextFormField and I want to validate it. With the validation, I want to get data from Firestore and that if the input value in the TextFormField exists in the Firestore database, it should return "Exists", else return null. I don't know if I'm doing the right thing but after in input the value and even if the value exists it doesn't return anything. Please help

class GenerateUID extends StatefulWidget {
  final String idAreadyExistsString;
  final String noSPacesAllowedString;
  final String fieldCannotBeEmptyString;
  const GenerateUID(
      {super.key,
      required this.idAreadyExistsString,
      required this.noSPacesAllowedString,
      required this.fieldCannotBeEmptyString});

  @override
  State<GenerateUID> createState() => _GenerateUIDState();
}

class _GenerateUIDState extends State<GenerateUID> {
  TextEditingController employeeIDController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Form(
        key: _formkey,
        child: TextFormField(
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("[0-9]")),
            LengthLimitingTextInputFormatter(10)
          ],
          controller: employeeIDController,
          style: const TextStyle(
              color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20),
          onChanged: (value) {
            _formkey.currentState?.validate();
          },
          validator: (value) {
            FirebaseFirestore.instance
                .collection("ADMIN IDS")
                .where("ID", isEqualTo: value)
                .get()
                .then((valuess) {
              if (valuess.docs.isNotEmpty) {
                return widget.idAreadyExistsString;
              }
            });

            if (value!.contains(" ")) {
              return (widget.noSPacesAllowedString);
            }

            if (value.isEmpty) {
              return (widget.fieldCannotBeEmptyString);
            }
            return null;
          },
        ),
      )),
    );
  }
}
1

There are 1 answers

1
A-E On BEST ANSWER

Firstly, i was on hurry. I have explained my solution in pseudo code, you need to write your code based on the idea.

here

class MyApp extends StatefulWidget{

List<String> ids = [];

  MyApp({super.key});

  void initState(){
    super.initState();
    initiateIdsList();

  }

  void initiateIdsList()async{
// initialize your list here, refactor the following pseudo code
    await FirebaseFirestore.instance
                .collection("ADMIN IDS").get().then((v){
                  v.forEach(e){
                    ids.add(e);
                  }
                });
  }

  @override
  Widget build(BuildContext context) {
    
    YourTFF(
      validator: (value){

        if (value!.contains(" ")) {
              return (widget.noSPacesAllowedString);
            }

            if (value.isEmpty) {
              return (widget.fieldCannotBeEmptyString);
            }
            if(ids.contains(value)){
              print('already exist');
            }
            return null;
      }
    );
  }

}

This is because we can't mark the validator callback as an asynchronous function.

Hope it helps you.