Flutter | routing management

Posted by abhi201090 on Tue, 15 Feb 2022 03:43:33 +0100

What is routing?

For mobile developers, routing refers to page, activity in Android and Wie ViewController in ios To put it simply, it maps the page Jump relationship. Of course, it also includes all functions related to jump Routing management is to manage these pages, direct jump, communication mode, etc


1. Create a new route and name it NewRoute

class NewRoute extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FlutterStudy"),
      body: Center(
        child: Text(
          "This is new route",
          style: Theme.of(context).textTheme.headline3,

2. Create a text button and click to jump

    child: Text("Click jump"),
    textColor: Colors.red,
    onPressed: () {
        //Navigate to the new route
        Navigator.push(context, MaterialPageRoute(builder: (context) {
            return NewRoute();


MaterialPageRoute is a component provided by the Material component library. It can switch animation in the same style as the platform page switching animation for different platforms

MaterialPageRoute inherits from the PageRoute class. PageRoute is an abstract class that represents a modal route page in the whole screen space, which defines the relevant interfaces and attributes of excessive animation during route construction and switching; If you want to customize the route switching animation, you can inherit PageRoute to implement it yourself

  • Construction method
  required this.builder,
  RouteSettings? settings,
  this.maintainState = true,
  bool fullscreenDialog = false,
  • builder

It is a callback function of WidgetBuilder type, which is used to build the specific content of the route, and the return value is a widget;

This callback is usually implemented to return an instance of the new route

  • setting

Example: the name of the initial route, whether it contains the route information, etc

  • maintainState

By default, when a new route is stacked, the original route will still be saved in memory. If you want to release the resources occupied by the route when it is useless, you can set it to false

  • fullscreenDialog

Indicates whether the new route is a full screen modal dialog box. If this parameter is true in ios, the new page will slide in from the bottom instead of the horizontal direction


Navigator is a route management component that provides methods to open and exit routes

The Navigator manages the active route collection through the stack. Usually, the page displayed on the screen is the route at the top of the stack

Open a page

    return Navigator.of(context)!.push(route);

Put the given route into the stack (open the page) and return the future object, which is used to receive the data returned when the route is out of the stack.

Close a page


Route the top of the stack out of the stack, and reslut is the data to be returned to the previous page

Routing value

  TipRoute({Key key, this.text}) : super(key: key);

  final String text;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Tips"),
      body: Padding(
          padding: EdgeInsets.all(18),
          child: Center(
            child: Column(
              children: <Widget>[
                  onPressed: () => Navigator.pop(context, "I am the return value"),
                  child: Text("return"),

The code is very simple. Add an appbar in the interface, display a text and a RaisedButton in the middle, click pop and pass in the value to be returned

  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () async {
          await Navigator.push(context, MaterialPageRoute(builder: (context) {
            return TipRoute(text: "I am the parameter");
          })).then((value) => print("Route return value $value"));
        child: Text("Open prompt page"),

In the onPressed method, this function is executed asynchronously, and finally the return value is printed out

If you don't know about async, check out this article, Dart, check as you use

Run the above code and click "open prompt page". The effect is as follows

Printed results

I/flutter (23778): Route return value I am the return value

It should be noted that

​ 1. Parameters are passed in through the construction method

​ 2. If you click the upper left corner or the return button to return, the value returned by the page is null

Named route

For a route with a name, give a name to the route, and you can directly open the route through the name

Routing table

The routing table is a map, the key is the routing name, and the value is a callback function of the builder, which is used to generate the corresponding routing widget. As follows:

final Map<String, WidgetBuilder>? routes;

Register routing

In MaterialApp, add the routes attribute as follows:

  return MaterialApp(
    //app name
    title: 'FlutterStudy',
    theme: ThemeData(
      primarySwatch: Colors.red,
    routes: {
      "new_page": (context) => NewRoute(),
      "/": (context) => MyHomePage(title: "Flutter Study")
    //Application home page routing
    home: MyHomePage(title: 'Flutter Study'),

Open the routing page

	child: Text("custom Button"),
	onPressed: () {
	Navigator.pushNamed(context, "router_test");

In the event of clicking, jump to the routing page for

Named route delivery with parameters

  "new_page": (context) => NewRoute(),

Register in the routing table

  Widget build(BuildContext context) {
    var args = ModalRoute.of(context).settings.arguments;

Accept parameters

Navigator.pushNamed(context, "new_page",arguments: "Hello World");

Just send data when jumping

Route generation hook

When opening some pages, you may need to do some permission detection, such as whether the user logs in and needs a password. If you have to judge every time you open the route, it will be very troublesome. This situation can be realized through MaterialApp

MaterialApp has an ongeneraterote attribute, which may be called when opening the route. The reason why it is possible is that when calling navigator When pushnamed() opens the route, if the specified route has been registered in the route table, it will call the builder function in the route table to generate the route component; If there is no registration in the routing table, ongeneraterote will be called to generate a route.

  ... //Omit irrelevant code
  onGenerateRoute:(RouteSettings settings){
      return MaterialPageRoute(builder: (context){
           String routeName = settings.name;
       // If the accessed routing page needs to be logged in, but is not currently logged in, you can directly return to the login page for routing,
       // Guide users to log in; In other cases, the route is opened normally.

reference material:

Flutter official website Actual combat of Flutter