AutoRoute In Flutter
For routing in a flutter, one must compose a great deal of code and check validations before exploring navigating with one screen then onto the next. This cycle can be simplified with code generation. When a project gets greater and greater in Flutter, it’s the ideal opportunity to utilize named routes, and implementing routing in flutter is tedious.
We can save time by producing all the routes ourselves and utilize the auto_route package and code generation for your flutter application.
auto_route | Flutter Package
AutoRoute is a declarative routing solution, where everything needed for navigation is automatically generated for you…pub.dev
In this article, we will explore the AutoRoute In Flutter. We will also implement a demo program using the auto_route package and code generation for your flutter applications.
Table Of Contents::
Introduction:
AutoRoute is a definitive routing arrangement, where everything required for navigation is automatically generated for you. We will make a basic application utilizing the auto_route package and code generation.
Demo Module ::
This demo video shows how to use an AutoRoute in a flutter and shows how AutoRoute will work using the auto_route package and code generation in your flutter applications, and show how all pages will navigating easily they will be shown on your device.
Implementation:
Step 1: Add the dependencies
Add dependencies to pubspec — yaml file.
dependencies:
auto_route:
Step 2: Add the dev dependencies
Add dev dependencies to pubspec — yaml file.
dev_dependencies:
build_runner:
auto_route_generator:
Step 3: Import
import 'package:auto_route/auto_route.dart';
Step 4: Run flutter packages get in the root directory of your app.
Step 5: Enable AndriodX
Add this to your gradle.properties file:
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
How to implement code in dart file :
You need to implement it in your code respectively:
Create a new dart file called home_page.dart
inside the lib
folder.
On this homepage, we will create a three-button. In three-button, we will navigate three different screens.
Now, we will deeply define all three page and code shown below:
Create a new dart file called first_page.dart
inside the lib
folder.
On the first page, we will take single construction ‘info’ in the string and called the class on the home page.
import 'package:flutter/material.dart';
class FirstPage extends StatelessWidget {
const FirstPage({
Key key,
@required this.info,
}) : super(key: key);
final String info;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
backgroundColor: Colors.black,
title: Text("First Page"),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(info,style: TextStyle(fontSize: 22),),
],
),
),
),
);
}
}
Create a new dart file called second_page.dart
inside the lib
folder.
On the second page, we will take two construction, “name” in the string and “emp” in integer, and called the class on the home page.
import 'package:flutter/material.dart';
class SecondPage extends StatelessWidget {
const SecondPage({
Key key,
@required this.name,
@required this.emp,
}) : super(key: key);
final String name;
final int emp;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
backgroundColor: Colors.black,
title: Text("Second Page"),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Name : $name",
style: TextStyle(fontSize: 22),),
Text("Employee : $emp",
style: TextStyle(fontSize: 22),),
],
),
),
),
);
}
}
Create a new dart file called third_page.dart
inside the lib
folder.
On the third page, we will take two construction, “name” and “dsg,” in the string, and called the class on the home page.
import 'package:flutter/material.dart';
class ThirdPage extends StatelessWidget {
const ThirdPage({
Key key,
@required this.name,
@required this.dsg,
}) : super(key: key);
final String name;
final String dsg;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
backgroundColor: Colors.black,
title: Text("Third Page"),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Name : $name",style: TextStyle(fontSize: 22),),
Text("Designation : $dsg",style: TextStyle(fontSize: 22),),
],
),
),
),
);
}
}
Create a new dart file called router.dart
inside the lib
folder.
To generate routes utilizing the auto_route package, we need to annotate on the Router class with AdaptiveAutoRouter(), which accepts a list of routes as an argument.
In this FlutterRouter class, we have accepted AutoRoute as a type of list. If you are developing this android application, you can take MaterialRoute or develop it just for iOS, and you can take CupertinoRoute. Its name should be prefixed with $ to get a generated class with a similar name minus the $. $Router => Router.
AdaptiveRoute and AutoRoute can deal with the page progress animation as per the stage you are utilizing, Android or iOS.
Now generate the code using build_runner you have to run this command in your terminal.
flutter packages pub run build_runner watch
If you want to build fresh and any conflict will occur, you can also use the command given below.
flutter pub run build_runner watch –delete-conflicting-outputs
This command will generate a router.gr.dart file in your directory which will look like the underneath.
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// AutoRouteGenerator
// **************************************************************************
// ignore_for_file: public_member_api_docs
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import '../pages/first_page.dart';
import '../pages/home_page.dart';
import '../pages/second_page.dart';
import '../pages/third_page.dart';
class Routes {
static const String homePage = '/';
static const String firstPage = '/first-page';
static const String secondPage = '/second-page';
static const String thirdPage = '/third-page';
static const all = <String>{
homePage,
firstPage,
secondPage,
thirdPage,
};
}
class FlutterRouter extends RouterBase {
@override
List<RouteDef> get routes => _routes;
final _routes = <RouteDef>[
RouteDef(Routes.homePage, page: HomePage),
RouteDef(Routes.firstPage, page: FirstPage),
RouteDef(Routes.secondPage, page: SecondPage),
RouteDef(Routes.thirdPage, page: ThirdPage),
];
@override
Map<Type, AutoRouteFactory> get pagesMap => _pagesMap;
final _pagesMap = <Type, AutoRouteFactory>{
HomePage: (data) {
return buildAdaptivePageRoute<dynamic>(
builder: (context) => const HomePage(),
settings: data,
);
},
FirstPage: (data) {
final args = data.getArgs<FirstPageArguments>(nullOk: false);
return buildAdaptivePageRoute<dynamic>(
builder: (context) => FirstPage(
key: args.key,
info: args.info,
),
settings: data,
);
},
SecondPage: (data) {
final args = data.getArgs<SecondPageArguments>(nullOk: false);
return buildAdaptivePageRoute<dynamic>(
builder: (context) => SecondPage(
key: args.key,
name: args.name,
emp: args.emp,
),
settings: data,
);
},
ThirdPage: (data) {
final args = data.getArgs<ThirdPageArguments>(nullOk: false);
return buildAdaptivePageRoute<dynamic>(
builder: (context) => ThirdPage(
key: args.key,
name: args.name,
dsg: args.dsg,
),
settings: data,
);
},
};
}
/// ************************************************************************
/// Arguments holder classes
/// *************************************************************************
/// FirstPage arguments holder class
class FirstPageArguments {
final Key key;
final String info;
FirstPageArguments({this.key, @required this.info});
}
/// SecondPage arguments holder class
class SecondPageArguments {
final Key key;
final String name;
final int emp;
SecondPageArguments({this.key, @required this.name, @required this.emp});
}
/// ThirdPage arguments holder class
class ThirdPageArguments {
final Key key;
final String name;
final String dsg;
ThirdPageArguments({this.key, @required this.name, @required this.dsg});
}
In main. Dart file to notify our application to utilize these generated routes to determine the builder in your MaterialApp widget.
import 'package:auto_route/auto_route.dart';
import 'package:auto_route_demo/router_page/router.gr.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: ExtendedNavigator.builder(
router: FlutterRouter(),
initialRoute: Routes.homePage,
builder: (_, navigator) => Theme(
data: ThemeData.dark(),
child: navigator,
),
),
debugShowCheckedModeBanner: false,
);
}
}
Presently, on the home page, we will call onPressed() in a button. To navigate utilizing generated routes, you should utilize ExtendedNavigator class, which comes from the auto_route package.
ExtendedNavigator.root.push(“route name”);
In this flat button, navigate to FirstPage, which has one argument in the constructor is the info: “Hello Flutter Dev’s.”
In this flat button, navigate to SecondPage, which takes two arguments in the constructor are name: “Flutter Dev’s” and emp: 165.
In this flat button, navigate to ThirdPage, which takes two arguments in the constructor are name: “Flutter Dev’s” and dsg: “Software Engineer.”
Code File:
https://gist.github.com/ShaiqAhmedkhan/3dd51bd7b32c99708c42e24009100f03#file-router_home_page-dart
Conclusion:
In the article, I have explained the basic structure of the AutoRoute in a flutter; you can modify this code according to your choice. This was a small introduction to AutoRoute On User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information in Trying up the AutoRoute in your flutter projects. We will show you the AutoRoute is?, and shows how to use an AutoRoute in a flutter and shows how AutoRoute will work using the auto_route package and code generation in your flutter applications, So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
find the source code of the Flutter AutoRoute Demo:
flutter-devs/flutter_auto_route_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.