Flutter ZERO Boilerplate Routing With Auto Route

Navigation and Routing take too much code and effort to implement. Two-Three lines of code have to be written for routing from one screen to another and in the end, it is not maintainable at all and becomes robust. We somehow need a way to generate one file for navigation purposes that can be easily maintained and has less boilerplate in order to be readable. If you are going to implement a router yourself, there's still a lot of boilerplate.

All of this changes with the package auto_route which works elegantly with code generation. This way you can reduce the boilerplate while still having the ability to customize the routes to your heart's content.

What is AutoRoute?

It's a flutter navigation package that allows for strongly-typed arguments passing, effortless deep-linking. It uses code generation to simplify routes setup i.e reduce the boilerplate code. It requires only a minimal amount of code to generate everything needed for navigation.

Why AutoRoute?

  • For clean Route setup
  • To reduce boilerplate code

What we gonna build?

The starter project contains the individual page widgets already pre-built so that we can focus purely o navigation.

Demonstration Video

Adding dependencies

pubspec.yaml:

dependencies:

  flutter:

    sdk: flutter

  auto_route: ^2.2.0

  cupertino_icons: ^1.0.2

 

dev_dependencies:

  flutter_test:

    sdk: flutter

  auto_route_generator: ^2.1.0

  build_runner: ^2.0.3

Router class

It's a center point of navigation and takes only a few lines of code.

router.dart

@MaterialAutoRouter(

  routes: <AutoRoute>[

    AutoRoute(page: FirstPage, initial: true),

    AutoRoute(page: SecondPage),

    AutoRoute(page: ThirdPage),

  ],

)

class $Router {}

To make the FirstPage as initial, we need to mark boolean initial as true( just like we make it as "/" slash notation)

You can use CustomRoute instead of AutoRoute to make any customization in the routing.

Now its time to run our favorite command to generated code for auto_route(on the terminal)

flutter pub run build_runner watch –delete-conflicting-outputs

Plugin Router into Flutter

After generating the the router class, its time to hook it up with MaterialApp

class MyApp extends StatelessWidget {

  final router = r.Router();

  @override

  Widget build(BuildContext context) {

    return MaterialApp.router(

      routerDelegate: router.delegate(),

      routeInformationParser: router.defaultRouteParser(),

      title: 'Auto Route',

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

    );

  }

}


First Page

import 'package:auto_route/auto_route.dart';

 

import 'package:auto_route_navigation/router.gr.dart';

import 'package:flutter/material.dart';

 

class FirstPage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text("First Page"),

      ),

      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,

          children: [

            Material(

              color: Colors.blue,

              child: TextButton(

                  onPressed: () {

                    AutoRouter.of(context)

                        .push(SecondPageRoute(userId: "UNIQUE ID"));

                  },

                  child: Text(

                    "Go to Second",

                    style: TextStyle(color: Colors.white),

                  )),

            ),

            const SizedBox(

              height: 20,

            ),

            Material(

              color: Colors.blue,

              child: TextButton(

                  onPressed: () {

                    AutoRouter.of(context).push(

                        ThirdPageRoute(heading: "Auto Navigation", rank: 1));

                  },

                  child: Text(

                    "Go to Third",

                    style: TextStyle(color: Colors.white),

                  )),

            ),

          ],

        ),

      ),

    );

  }

}

Added navigation code on "Go to Second" callback and "Go to Third" callback.

Single-Argument Route

The SecondPage widget takes in a single argument into a constructor.

When auto_route sees a single-parameter constructor, it will always make sure that the passed-in argument present and that it is of the correct type. Since auto_route uses the default navigator API with named routes, passing arguments to a new route uses the arguments parameter of the pushNamed method.

import 'package:auto_route/auto_route.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

 

class SecondPage extends StatelessWidget {

  final String userId;

  const SecondPage({

    Key? key,

    required this.userId,

  }) : super(key: key);

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text("Second Page"),

        leading: IconButton(

          onPressed: () {

            AutoRouter.of(context).pop(); // Pop Navigation using                                              auto_route

          },

          icon: Icon(

            Icons.arrow_back,

            size: 15,

            color: Colors.white,

          ),

        ),

      ),

      body: Center(

        child: Text(

          userId,

          textAlign: TextAlign.center,

        ),

      ),

    );

  }

}

Multi-Arguments Route

The ThirdPage widget takes in two arguments in the constructor.

import 'package:auto_route/auto_route.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

 

class ThirdPage extends StatelessWidget {

  final String heading;

  final int rank;

 

  const ThirdPage({Key? key, required this.heading, required this.rank})

      : super(key: key);

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text("Third Page"),

        leading: IconButton(

          onPressed: () {

            AutoRouter.of(context).pop();

          },

          icon: Icon(

            Icons.arrow_back,

            size: 15,

            color: Colors.white,

          ),

        ),

      ),

      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,

          children: [

            Text(

              heading,

              textAlign: TextAlign.center,

            ),

            Text(

              '$rank',

              textAlign: TextAlign.center,

            ),

          ],

        ),

      ),

    );

  }

}

For More Info, CLICK HERE

#Flutter

Comments

Popular posts from this blog

How to use Custom Icons in Flutter(Using SVG or Icon Font)?

Flutter Video Feeds (Like Instagram or Facebook)