Clean Route Navigation Using Generated Routes In Flutter
Navigation in Flutter can be done in one of two ways. Named routes, or pushing Routes explicitly by instantiating a Page Route and passing it to the Navigator.
Pushing routes can become quite explicit and sharing logic between them becomes difficult.
Logic like checking if the user is authenticated for a specific view. In this tutorial ,
we’ll set up a Router for Flutter and allow you to use named routes with parameters.
Setup
import 'package:flutter/material.dart'; import 'package:learn_database/route/route_genarate.dart'; import 'package:learn_database/screens/home_screen.dart'; void main (){ runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp();
Router / Routing Setup
The MaterialApp provides you with a property called onGenerateRoute
where you can pass in a Function that returns
a Route
and takes in RouteSettings
. This is what we'll use.
To keep things neat, we'll create a Router class.
In it, we'll create a static function with the signature mentioned above. Create a route_genarate.dart file.
import 'package:flutter/material.dart'; class RouteGenerator { static Route generateRoute(RouteSettings settings) { switch (settings.name) { case '/': return MaterialPageRoute(builder: (_) => const HomeScreen()); case '/add-employee-screen': return MaterialPageRoute(builder: (_) => const AddEmlopyeeScreen()); default: return _errorPage(); } } static Route _errorPage() { return MaterialPageRoute(builder: (_) { return Scaffold( appBar: AppBar( title: const Text('Pages Are loading'), ), body: const Center( child: Text('Sorry rout are not founding!'), ), ); }); } }
The settings contain the route information of the requested route.
It provides two key things to us. The name, and the arguments. We’ll use the name to determine which view to return.
Update the generate Function to look like this.
switch (settings.name) { case '/': return MaterialPageRoute(builder: (_) => const HomeScreen()); case '/add-employee-screen': return MaterialPageRoute(builder: (_) => const AddEmlopyeeScreen()); default: return _errorPage(); } }
Now in your App, where you define your MaterialApp,
you’ll pass the generateRoute function to onGenerateRoute.
To define the home view as the starting view,
instead of setting the home property to a widget we’ll use initialRoute instead.
initialRoute: '/', onGenerateRoute: RouteGenerator.generateRoute
We are developing Mobile application and Web application for more detatils vist our web site www.appslanka.lk
0 Comments