free geoip
40

Named Routes in Dart for Android Studio

Named routes in Dart are a convenient and scalable way to navigate between screens in Flutter applications. Instead of manually…

Named routes in Dart are a convenient and scalable way to navigate between screens in Flutter applications. Instead of manually pushing pages with Navigator.push(), named routes allow you to assign identifiers (strings) to different screens. This approach makes code cleaner, especially in large apps.

Named Routes in Dart

In this tutorial, you will learn how to implement named routes using Android Studio and Dart with Flutter. We’ll go step-by-step from setting up routes to navigating between them, and provide clean sample code with proper class separation.

Step 1: Setup Your Main Route File

Create a main.dart file. This will be your entry point and contain the route table.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes Demo',
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/about': (context) => AboutScreen(),
      },
    );
  }
}

Step 2: Create the HomeScreen Class

File: home_screen.dart

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/about');
          },
          child: Text("Go to About Page"),
        ),
      ),
    );
  }
}

Step 3: Create the AboutScreen Class

File: about_screen.dart

import 'package:flutter/material.dart';

class AboutScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("About")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text("Back to Home"),
        ),
      ),
    );
  }
}

Advantages of Named Routes

  • Centralized route management
  • Cleaner code for large apps
  • Easy to navigate from any widget

For more advanced routing and state management, you can explore packages like GoRouter, a popular routing library supported by the Flutter team.

Named routing is essential when building structured apps in Dart using Android Studio. With centralized route definitions and separation of UI components, your app becomes easier to manage and scale.

rysasahrial

Leave a Reply

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