I am trying switch to a different screen in Flutter project using onPressed but it is not generating any outcome not sure what is the reason.
Here is the homescreen page:
onPressed: () {
const User_Profile();
print("Hello");
},
Here is the user profile:
class User_Profile extends StatefulWidget {
const User_Profile({Key? key}) : super(key: key);
@override
State<User_Profile> createState() => _user_profileState();
}
class _user_profileState extends State<User_Profile> {
@override
Widget build(BuildContext context) {
return const Text("User Profile");
}
}
Question:
How to switch screens using Onpressed? What am I doing wrong noting that the word Hello for debugging is printed everytime.
3
Answers
Try below code and use
Navigator.push
refer navigationYou have to use a function instead of your class like this:
call this:
instead of this:
as you know you can’t go to a specific page by calling the constructor method in a class. you have 2 ways:
use
Navigator.push
like this:and you can send the parameters to the next page by sending by constructor parameters like:
User_Profile(name: 'yourName')
.2) you can useNavigator.pushNamed
. you can define routeName in your main class of the project like this:as you see you defined a routeName
'/user_profile'
and you can useNavigator.pushNamed
and if you want to pass parameters to the next page you have to usearguments
like this:and this code is for getting the arguments that you’ve passed in your User_Profile :
I recommend you to use the second way to know all your routes of your projects.
Good Luck;)