Home > Back-end >  Switching to another Screen using onPressed not working properly
Switching to another Screen using onPressed not working properly

Time:11-26

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.

CodePudding user response:

Try below code and use Navigator.push refer navigation

  ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => User_Profile(),
              ),
            );
          },
          child: const Text('User Profile'),
        ),

CodePudding user response:

You have to use a function instead of your class like this:

Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));

call this:

 onPressed: () {
                                       Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));
                                      },

instead of this:

   onPressed: () {
                                        const User_Profile();
                                        print("Hello");
                                      },
  • Related