free geoip
46

How to Navigate Between Screens in Dar

Navigating between screens is a fundamental feature when building mobile apps using Dart and Flutter. If you’re developing with Android…

Navigating between screens is a fundamental feature when building mobile apps using Dart and Flutter. If you’re developing with Android Studio, this guide will walk you through the complete steps of how to implement simple and named routes to switch from one screen to another effectively.

Navigate Between Screens in Dart

Flutter, powered by Dart, offers two primary ways to manage screen transitions: using Navigator.push() for direct transitions and defining named routes for structured navigation. This tutorial covers both methods with clean code examples and separate Dart classes.

Step-by-Step Navigation Setup in Dart

1. Create the Main Entry (main.dart)

This is where you define the app’s entry point and named routes.

import 'package:flutter/material.dart';
import 'home_screen.dart';
import 'second_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Navigation Demo',
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/second': (context) => SecondScreen(),
      },
    );
  }
}
2. First Screen (home_screen.dart)

A button to navigate to the second screen using a named route.

import 'package:flutter/material.dart';

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

Simple second screen with a back button.

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go Back'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

Best Practices

For further Flutter navigation documentation, you can check this helpful guide on the Flutter official documentation.

This method works flawlessly in Android Studio as long as the flutter and dart plugins are properly installed and your project is correctly configured.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *