I would recommend trying to avoid GlobalKey
usage in your app, see this question for further information.
Now to fix your problem you can approach this using many state management techniques, I will give you an example of the simplest technique, while not the best way, will work.
First you declare a TextEditingController
in your login screen, then you will pass down this controller until you pass it to the CustomTextField()
. The TextEditingController
will contain the text in the textfield it is used on. See the code snippet below for more details.
class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() =>_LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
TextEditingController controller;
@override
void initState() {
controller = TextEditingController();
super.initState();
}
@override
void dispose() {
controller.dispose(); //prevents memory leak
}
@override
Widget build(BuildContext context) {
// Here you can check if the TextField is empty or not
if (controller.text == null || controller.text == "") {
print("empty");
} else {
print("not empty");
}
return FormCard(controller: controller);
}
class FormCard extends StatelessWidget {
final TextEditingController controller;
FormCard({this.controller});
@override
Widget build(BuildContext context) {
return CustomTextField(controller: controller);
}
}
/* CustomTextField is stateful because sometimes
stateless widgets do not update textfields text when
equipped with controllers
*/
class CustomTextField extends StatefulWidget {
final TextEditingController controller;
CustomTextField({this.controller});
@override
_CustomTextFieldState createState() =>_CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
);
}
}
You will need to place all classes in the same file or import all of them as mahi stated.
This technique will be a headache in larger applications, look up State Management concepts in flutter to find much better ways of implementation.