Search code examples
flutterflutter-layoutflutter-dependenciesflutter-web

How do i make a TextEditingController Required in a stateful widget


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


Solution

  • 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,
          // ...
        );
      }
    }