Flutter learning notes “plug ins”: routing plug-in fluro

Time:2021-5-11

Flutter itself providesNavigatorWidget to implement the routing function of the application. But the use of some routing plug-ins can help us more easily and quickly realize the functions of jump and value transfer between the pages of the flutter application.

In this note, we’ll mainly learn about the fluro plug-in.

1. The project introduces fluro

In order to use any third-party plug-in in the flutter application, it needs to be introduced into the project first.

Open thepubspec.yamlFile, independenciesAdd the configuration code of fluro under the property:

dependencies:
  fluro: ^1.6.3

The reference code screenshot is as follows:

Flutter learning notes

Note: 1.6.3 is the latest version number of fluro (2020.04.13). When you use it in the future, it is recommended to go firstOfficial websiteLook at the latest version number and change it to the latest version number when configuring.

2. Basic use of fluro

The most basic function of fluro is to “jump to the page”. Other functions such as “pass value” and “return” are advanced operations for our dish chicken, so let’s not talk about them first. Let’s learn basic gymnastics first!

2.1 establish routing file

Generally, we will create a new folder in the Lib directory of the project (for example:lib/routers), which is specially used to store the configuration code related to routing.

2.2 routing configuration

Create alib/routers/routes.dartFile is used for routing configuration

import 'package:flutter/material.dart';
//Introduction of fluro
import 'package:fluro/fluro.dart';
//Introduce the page file to jump to
import 'package:flutter_fluro_demo/home_page.dart';
import 'package:flutter_fluro_demo/login_page.dart';

class Routes {
  //The path string of each page
  static String home = '/home';
  static String login = '/login';
  //Create a configureroutes method for route configuration
  static void configureRoutes(Router router) {
    //Configure home page routing
    router.define(home, handler: Handler(
        handlerFunc: (BuildContext context, Map<String, List<String>> params) {
          return HomePage();
        },
      ),
    );
    //Configure login page routing
    router.define(login, handler: Handler(
        handlerFunc: (BuildContext context, Map<String, List<String>> params) {
          return LoginPage();
        }
      ),
    );
  }
}

In this configuration file, we take “home page” and “login page” as examples to make the most basic routing configuration.

2.3 route static processing

In order to make it convenient for us to use the route in each page later, I suggest (the official also suggests) to make a static processing for the route first.

staylib/routersCreate another one inapplication.dartFile, add the following code:

import 'package:fluro/fluro.dart';

class Application {
  static Router router;
}

In this code, we create an application object and set a static property router.

In the next step of global injection routing, we will callRouter()Method is saved in theApplication.routerProperty. In this way, when routing is used in subsequent pages, you can directly use theApplication.routerTo get the routing object without calling it repeatedlyRouter()There’s no way.

2.4 global injection routing

After the configuration is completed, the next step is to create the project entry filemain.dartTo make our route work, we inject routes into the.

import 'package:flutter/material.dart';
import 'package:fluro/fluro.dart';
import ' package:flutter_ fluro_ demo/routers/routes.dart'; //  Routing profile
import ' package:flutter_ fluro_ demo/routers/application.dart';  //  Route static file

void main() {
  final router = Router();  //  Get Route Object
  Routes.configureRoutes(router);  //  Call route configuration method
  Application.router = router;  //  Static route object
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      Ongenerateroute: application.router.generator, // configure the route to materialapp
      // ...
    );
  }
}

2.5 route jump

The simplest way to jump in fluro is through thenavigateTo()Method

import 'package:flutter_fluro_demo/routers/application.dart';
// ...
Application.router.navigateTo(context, '/home');

The reference code screenshot is as follows:

Flutter learning notes
At this point, we can achieve the simplest route jump.

3. Advanced use of fluro

After learning the basic use of routing, we need to increase the difficulty of losing.

3.1 split routing profile

In the previous routing basic usage, we put all the configuration about routing in theroutes.dartIn the file, when the pages of our project gradually increase, the file will become larger and larger, the code will be more and more, and the later maintenance will be more and more inconvenient.

So, we have toroutes.dartSplit the code in the file.

routes.dartThe original code is as follows:

Flutter learning notes

As you can see from the code in the figure, most of the code for routing operations is concentrated inhandlerAttribute, so we put eachhandlerAttribute values are extracted.

staylib/routersCreate another file in:route_handlers.dart, put the split code in:

import 'package:flutter/material.dart';
import 'package:fluro/fluro.dart';

import 'package:flutter_fluro_demo/home_page.dart';
import 'package:flutter_fluro_demo/login_page.dart';

Handler homeHandler = Handler(
  handlerFunc: (BuildContext context, Map<String, List<String>> params) {
    return HomePage();
  },
);

Handler loginHandler = Handler(
  handlerFunc: (BuildContext context, Map<String, List<String>> params) {
    return LoginPage();
  },
);

After this split, our originalroutes.dartThe file becomes very clean.

import 'package:fluro/fluro.dart';
import './route_handlers.dart';

class Routes {
  static String home = '/home';
  static String login = '/login';

  static void configureRoutes(Router router) {
    router.define(home, handler: homeHandler);
    router.define(login, handler: loginHandler);
  }
}

3.2 routing parameters

Although we divide the routing parameter into advanced usage, we should be aware that the routing parameter function is essential in any app. What’s more, fluro’s routing parameters are so easy ~

In fact, routing parameter transfer is simply understood as a process of taking out. For example, if we want to transfer the data of the home page to the detail page, then the home page is the business, the detail page is you who stay at home all day, and fluro is our take away rider.

After understanding the process of parameter transfer, we can start to move bricks.

Step 1: configure the parameters to be received on the de TiAl page

The code in the detail page is as follows:

import 'package:flutter/material.dart';

class DetailPage extends StatelessWidget {
  DetailPage({this.detailId});
  final String detailId;

  //...
}

Here we define adetailId, which is used to receive the parameters passed from home.

The code screenshot of my case is as follows:

Flutter learning notes

Step 2: set the parameters to be passed on the home page

The routing jump and parameter transfer codes of the home page are as follows:

RaisedButton(
  Child: text ('Go to details page '),
  onPressed: () {
    Application.router.navigateTo(context, '/detail/001');
  },
),

/detail/001In/detailIt’s the path to the detail page,001This is the parameter we want to pass to the detail page.

Step 3: configure the detail route in the route configuration file

openlib/routers/routes.dartFile to configure the route of detail as follows:

class Routes {
  // ...
  static String detail = '/detail/:id';

  static void configureRoutes(Router router) {
    // ...
    router.define(detail, handler: detailHandler);
  }
}

The reference code screenshot is as follows:

Flutter learning notes

detailHandlerError reporting is because we haven’t created this variable yet, so we won’t report an error after creating it in the next step.)

/detail/:idInidIt is a parameter name defined by ourselves, which is used to name the parameters passed through the home page.

Next, open it againlib/routers/routes_handlers.dartFile, configure the handler method of detail.

import 'package:flutter_fluro_demo/detail_page.dart';
// ...
Handler detailHandler = Handler(
  handlerFunc: (BuildContext context, Map<String, List<String>> params) {
    String id = params['id'].first; //  Get the parameters passed in the route through params
    return DetailPage(detailId: id);
  },
);

At this point, we have completed the parameter transfer from the home page to the detail page through routing.

Flutter learning notes

3.3 return to page

In flutter, there will be a return arrow in the upper left corner of the page after jumping, but sometimes we need to click other parts of the interface to return to the page, or we want to return to a specified interface.

3.3.1 return to previous page

The code returned by the page is simple:

RaisedButton(
  Child: text ('return to previous page '),
  onPressed: () {
    // flutter 
    Navigator.pop(context);
    // fluro
    // Application.router.pop(context);
  },
)

As can be seen from the above code, there are two ways to realize the function of “return to the previous page”: one is built-in of flutterNavigatorPop method provided by widget; The other is the pop method provided in fluro.

Here we list the native return mode of flutter, because the native return mode of flutter is more concise, so we prefer to use the route return function directlyNavigatorMethod.

3.3.2 return to the specified page

Fluro does not provide a special “return to the specified page” method (I have read the source code of fluro, I really can’t find it. If there is a mistake here, please let me know in the comments). So if we want to achieve the effect of “return to the specified page”, we can directly use thenavigateToThe implementation of page Jump method.

For specific code, please refer to the example code of “2.5 route jump” above.

3.4 management history

By default, a new route record will be registered in the route table for each route jump.

In fluronavigateTo()Method can set a third parameter to manage the routing history.

3.4.1 replacement history

Replacing history records means replacing “current page” records with “new page after jump” records. takenavigateTo()The third parameter of the method is set toreplace: trueThat’s it.

child: RaisedButton(
  Child: text ('Go to details page '),
  onPressed: () {
    Application.router.navigateTo(context, '/detail/001', replace: true);
  },
),

The reference code screenshot is as follows:

Flutter learning notes

When we jump from the “landing page” to the “home page”, then from the “home page” to the “details page”, and then click the return button in the upper left corner of the “details page”, we can find that we directly return to the “landing page”. Because there is no record of “home page” in our history.

3.4.2 clear history

In addition to replacing a history record,navigateTo()Method can also set the third parameter toclearStack: trueTo clear the history.

child: RaisedButton(
  Child: text ('Go to details page '),
  onPressed: () {
    Application.router.navigateTo(context, '/detail/001', clearStack: true);
  },
),

4. Finally

This is about the usage of fluro. If there are any knowledge points that have not been written, you can tell me in the comments, and I’ll add.

Recommended Today

Rust programming video tutorial corresponding content – error

Video address Headline address:https://www.ixigua.com/i676544267458235648…Station B address:https://www.bilibili.com/video/av78062009?…Netease cloud classroom address:https://study.163.com/course/introduction…. Explanation content 1. The error is divided into two categories: recoverable error and unrecoverable error(1) Recoverable errors usually represent situations in which it is reasonable to report errors to the user and retry operations, such as files not found. Result < T, E > is used […]