Move to Another Screen
Moving to Another Screen in Flutter
Flutter provides several ways to navigate between screens, but the most common method is using Navigator. Here is sample code to move to another screen:
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SecondScreen()),
);
Example 1: Move To Second Screen
Flutter provides the Navigator class to manage routes. Here’s a simple way to navigate to a new screen:
Step 1: Define a Screen
First, define a new screen as a StatelessWidget or StatefulWidget:
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: Center(
child: Text("Welcome to the second screen!"),
),
);
}
}
Step 2: Moving to the New Screen
Use the Navigator.push method to move to the new screen:
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SecondScreen()),
);
Navigating Back
To return to the previous screen, use the Navigator.pop method:
Navigator.pop(context);
Challenge
Create two screens, HomeScreen and AboutScreen. When you click a button on the home screen, navigate to the about screen.