I created a widget for a textfield that accepts password and I made use of stateful widget. Now I want to get the value of what is written in the text field in two different files but I can't make the texteditingcontroller requiredenter image description here
CodePudding user response:
You can make it like this:
First you have to create controller :
var _controller = TextEditingController();
Second add this controller to your textfield
TextField(
autofocus: true,
controller: _controller, // add controller here
decoration: InputDecoration(
hintText: 'Test',
focusColor: Colors.white,
),
),
and finally in your button check if controller is empty or not
CustomButton( onTap: () async { if (_controller.text.trim().isEmpty) { showCustomSnackBar( 'Password field is empty', context); } } )
just it
CodePudding user response:
Login Page should be something like this: declare the controller in the login page then you can pass the controller to other Widget including Passwordfield, the Login page now is the owner of the controller it initialize it and dispose it.
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
late TextEditingController _passwordController;
@override
void initState() {
_passwordController = TextEditingController();
}
@override
void dispose() {
_passwordController.dispose();
}
Widget build(BuildContext context) {
return Column(
children: <Widget>[
// Emailfield(),
Passwordfield(
controller: _passwordController,
),
],
);
}
}
in the Passwordfield edit the constructor to use the controller in this Widget:
class Passwordfield extends StatefulWidget {
final TextEditingController controller;
Passwordfield({Key? key, required this.controller,}) : super(key: key);
@override
_PasswordfieldState createState() => _PasswordfieldState();
}
class _PasswordfieldState extends State<Passwordfield> {
ValueChanged<String> onChanged = (value) {};
String hintText = "password";
bool hidepassword = true;
Widget build(BuildContext context) {
return TextField(
controller: widget.controller,
onChanged: onChanged,
obscureText: hidepassword,
// ...
);
}
}