Navigate on Button Click in Flutter

One of the core functions of developing a mobile app is navigating between displays. This procedure is straightforward and easy in Flutter, enabling developers to design seamless user experiences. We’ll look at how to go to a new screen when a button is clicked in this blog post.

1. Setting Up a Flutter Project

Before we dive into navigation, let’s set up a basic Flutter project. If you haven’t already, you can create a new Flutter project using the following command:

flutter create navigate_demo

Open the project in your favorite IDE or code editor.

2. Basic Navigation in Flutter

Flutter uses the Navigator widget to manage navigation and routing. The Navigator works with Routes, which represent different screens or pages in your application.

Here’s a simple example of navigating to a new screen when a button is clicked:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Navigation Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
          child: Text('Go to Second Screen'),
        ),
      ),
    );
  }
}

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!'),
      ),
    );
  }
}

3. Explanation of the Code

  1. MyApp Class:
    • This is the root of the application. It uses a MaterialApp widget to set up the app’s theme and home screen.
  2. FirstScreen Class:
    • This is the initial screen of the app. It contains an ElevatedButton which, when pressed, navigates to the SecondScreen.
  3. SecondScreen Class:
    • This is the destination screen. It displays a simple message.

When the button on the FirstScreen is clicked, the Navigator.push method is called. This method takes a BuildContext and a MaterialPageRoute as arguments. The MaterialPageRoute defines the route to the new screen.

4. Using Named Routes

For more complex applications, using named routes can make navigation easier to manage. Named routes provide a cleaner way to navigate between screens by defining route names and their corresponding widgets in the MaterialApp widget.

Here’s how you can use named routes in Flutter:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Navigation Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => FirstScreen(),
        '/second': (context) => SecondScreen(),
      },
    );
  }
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/second');
          },
          child: Text('Go to Second Screen'),
        ),
      ),
    );
  }
}

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!'),
      ),
    );
  }
}

5. Explanation of Named Routes

  1. MaterialApp Setup:
    • The MaterialApp widget now includes the initialRoute and routes properties.
    • initialRoute specifies the initial screen to display (in this case, the FirstScreen).
    • routes is a map that associates route names with their corresponding widget builders.
  2. Navigator.pushNamed:
    • In the FirstScreen, the Navigator.pushNamed method is used to navigate to the SecondScreen using the route name /second.

Named routes are particularly useful for larger applications with multiple screens, as they make the navigation logic more organized and maintainable.

Conclusion

Navigating to a new screen on a button click in Flutter is straightforward and flexible. Whether you use direct routes with MaterialPageRoute or named routes for more complex navigation, Flutter’s navigation system provides the tools you need to create seamless transitions between screens.