Home > OS >  How can i access a textEditingController created in another file in flutter
How can i access a textEditingController created in another file in flutter

Time:04-26

I have two files. File 1 has a nameController and file2 has emailController and passwordController. I want to access the nameController from file1 in file2 which has the .registerUsingEmailPassword() method .

file1

class UserName extends StatefulWidget {
const UserName({Key? key}) : super(key: key);

@override
State<UserName> createState() => _UserNameState();
}
  final _registerFormKey = GlobalKey<FormState>();
  final _nameTextController = TextEditingController();
  ...
Form(
   key: _registerFormKey,
    child:  TextFormField(
    controller: _nameTextController, 
  ..
  )); 
                 

 }

file2

  class SignUp extends StatefulWidget {
    const SignUp({Key? key}) : super(key: key);
    @override
    State<SignUp> createState() => _SignUpState();
    }

   class _MyEmailState extends State<SignUp> {  

   final _regFormKey = GlobalKey<FormState>();
   final _emailController = TextEditingController();
   final _passwordController = TextEditingController();
   ...
     if (_regFormKey.currentState!.validate()) {
     User? user = await FireAuth.registerUsingEmailPassword(
      name: _nameTextController.text, // I want to access this controller from 
      file1 
       email: _emailTextController.text, 
      password:_passwordTextController.text,
     );

 }
 
 }

Can somebody help please.

CodePudding user response:

You must be going from file 1 to file 2 through navigator, pass the data from nameController as an argument to the Navigator like,

Navigator.of(context).pushNamed('file2Route', arguments:nameController.text);

Get the text in file2 as

var nameText = ModalRoute.of(context)!.settings.arguments as String;

Then simply use the nameText in registerUsingEmailPassword() method.

If this is not the case, please do specify.

Cheers!!

CodePudding user response:

class SignUp extends StatefulWidget {
final TextEditingController nameController; // pass via constructor
  const SignUp({Key? key,required TextEditingController nameController}) : super(key: key);
@override
State<SignUp> createState() => _SignUpState();
}

then use in build like this

 if (_regFormKey.currentState!.validate()) {
 User? user = await FireAuth.registerUsingEmailPassword(
  name: widget.nameController.text, // use like this
   email: _emailTextController.text, 
  password:_passwordTextController.text,
 );
  • Related