I am making register and login pages in flutter and facing a problem as I want to use the same variables 'email' and 'password' declared inside class _MyHomePage in main.dart file
to another class SignupPage in signup.dart file.
I already imported the files but I can not use the values in both classes
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String _email = '';
String _password = '';
final formKey = new GlobalKey<FormState>();
FormType _formType = FormType.login;
bool validateAndSave() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
return true;
// print('Form is Valid Email: $_email, Password: $_password');
}
return false;
}
You can pass the data when you navigate your screen in following way.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUp(email: emailvariable,pass: passvariable),
),
in following way you can receive data
class SignUp extends StatefulWidget {
final email;
final pass;
SignUp({Key key,this.email,this.pass}) : super(key: key);
@override
_SignUpState createState() => _SignUpState();
}
now in state widget you can access email and pass variable as
widget.pass and widget.email
Pass values through class constructor
If you don't want to go back and forth you can use this
Just in the second page use like this
class Register extends StatefulWidget {
Register({Key key, this.email, this.pass});
final String email;
final String pass;
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
@override
Widget build(BuildContext context) {
print(widget.email);
print(widget.pass);
// to use state class values you need to use the widget as the parent class object
return Container(
);
}
}
To pass the values in constructor
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Register(email: email, pass: pass),
),
Store the values in global scope before routing to another page
If you have to route multiple times and even require these values further, you store the values in global file before routing to another page and access there
Make one file
library my_project.global;
// set default values for the initial run
String email = '';
String pass = '';
import 'global.dart' as global;
main() {
// import the global.dart file to access the variables across the application
global.email = '[email protected]';
print(global.email);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With