There are two ways of Flutter route jump: one is to use the system native jump method. The second is to use third-party frameworks like Fluro…

Flutter introduces the Fluro library

Brightest, Hippest, Coolest Router for Flutter

Open a pub. Dev/packages/fl… Find the latest version.

Add the dependent

dependencies:
  fluro: ^1.63.
Copy the code

Sample project (official text)

There is a very cute example project in the “Example” folder. Check it out. Otherwise, keep reading until you run.

Set up the

First, you define a new Router object by initializing it:

final router = Router();
Copy the code

It is convenient for you to store the router globally/statically so that you can access it in other areas of your application.

After instantiating the router, you need to define your routes and your Route Handlers:

var usersHandler = Handler(handlerFunc: (BuildContext context, Map<String.dynamic> params) {
  return UsersScreen(params["id"] [0]);
});

void defineRoutes(Router router) {
  router.define("/users/:id", handler: usersHandler);

  // it is also possible to define the route transition to use
  // router.define("users/:id", handler: usersHandler, transitionType: TransitionType.inFromLeft);
}
Copy the code

In the example above, the router would intercept a route such as/Users /1234 and route the application to UsersScreen, passing the value 1234 as a parameter to that page.

navigation

You can be in MaterialApp. Use the Router onGenerateRoute. Parameter through the router. generator function. To do this, pass a function reference to the onGenerate parameter, similar to onGenerateRoute: router.generator.

Then you can use navigator.push. The flutter routing mechanism then matches the routing path for you.

You can also manually push to a path yourself. Do it like this:

router.navigateTo(context, "/users/1234", transition: TransitionType.fadeIn);
Copy the code

The actual operation

Well, the official documentation may be a bit hazy, so let’s get real

Create three new files

  • \routes\Routes.dartThe routing file
  • \routes\Routes_handler.dartThe routing handler
  • \routes\fluro_convert_utils.dartParameter coding conversion tool, Fluro does not support Chinese parameter transmission

Setting a route

Device routing in main

import 'package:fluro/fluro.dart';
import 'package:smarthome/routes/routes.dart';

void main() {
  // Set the route
  finalrouter = Router(); Routes.configureRoutes(router); Routes.router = router; . }Copy the code

Routing Entry and Configuration (\routes\Routes.dart)

There are two steps here

  • Define address variables, such as:static String root = '/';
  • Define a route handler, such as:router.define(root, handler: appHandler); / / main page
///
/// Routing entry
/// Configuring a Route
///
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:smarthome/routes/routes_handler.dart';
import '.. /main.dart';

class Routes {
  /// routing
  static Router router;
  /// The home page
  static String root = '/';
  /// The welcome page
  static String welcome = '/welcome';
  /// The login page
  static String login = '/login';
  /// Registration page
  static String register = '/register';

  / / configure the route
  static void configureRoutes(Router router) {
    // No corresponding route was found
    router.notFoundHandler = Handler(handlerFunc: (BuildContext context, Map<String.dynamic> params) {
      print('route not found! ');
      return;
    });

    router.define(root, handler: appHandler); / / main page
    router.define(welcome, handler: welcomeHandler); / / welcome
    router.define(login, handler: loginHandler); / / login
    router.define(register, handler: registerHandler); / / register
  }

  /// Hop routing
  /// Path: indicates the routing address
  /// Params: parameter
  /// -Leonard: Transition
  /// Replace: substitution
  static Future push(BuildContext context, String path, {Map<String.dynamic> params, TransitionType transition = TransitionType.cupertino, bool replace = false.bool clearStack = false{})// Encode the parameters to solve the problem that there are special characters in the parameters, which affect the fluro route matching
    String query =  "";
    if(params ! =null) {
      int index = 0;
      for (var key in params.keys) {
        var value = Uri.encodeComponent(params[key]);
        if (index == 0) {
          query = "?";
        } else {
          query = query + \ "&";
        }
        query += "$key=$value"; index++; }}// print('navigateTo pass: $query');

    path = path + query;
    return router.navigateTo(context, path, transition:transition, replace: replace, clearStack: clearStack);
  }

  /// Return to previous page
  static pop() {
    / / the global contextBuildContext context = navigatorKey.currentState.overlay.context; router.pop(context); }}Copy the code

The routing handler (\routes\Routes_handler.dart)

There are two cases of handler

  • Return to the page without parameters
  • With Chinese parameters to do transcoding jump.
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:smarthome/routes/fluro_convert_utils.dart';
import 'package:smarthome/views/root.dart';
import 'package:smarthome/views/home/device.dart';
import 'package:smarthome/views/welcome/login.dart';
import 'package:smarthome/views/welcome/register.dart';
import 'package:smarthome/views/welcome/welcome.dart';

/// The home page
var appHandler =
    Handler(handlerFunc: (BuildContext context, Map<String.dynamic> params) {
  // Go back to the page without parameters
  return Root();
});

/// equipment
var deviceHandler =
    Handler(handlerFunc: (BuildContext context, Map<String.dynamic> params) {
  // The parameter is not in Chinese
  String device = params['device']? .first;return Device(device: device);
});

/// Action selection
var selectDoHandler =
    Handler(handlerFunc: (BuildContext context, Map<String.dynamic> params) {
  String gatewayIdString = params['gatewayId']? .first;String controlString = params['control']? .first;int gatewayId = int.parse(gatewayIdString);
  if(controlString ! =null) {
    /// Parameter has Chinese, do conversion after jump page
    Map<String.dynamic> control = FluroConvertUtils.string2map(controlString);
    SelectDo(gatewayId: gatewayId, haveControl: control);
  }
  return SelectDo(gatewayId: gatewayId);
});

Copy the code

Fluro parameter coding conversion tool (\routes\fluro_convert_utils.dart)

import 'dart:convert';

/// Fluro parameter coding conversion tool class
class FluroConvertUtils {
  /// Before fluro transmits Chinese parameters, it should be converted. Fluro does not support Chinese transmission
  static String fluroCnParamsEncode(String originalCn) {
    return jsonEncode(Utf8Encoder().convert(originalCn));
  }

  /// Fluro takes out the parameters and analyzes them
  static String fluroCnParamsDecode(String encodeCn) {
    var list = List<int> ();///String decoding
    jsonDecode(encodeCn).forEach(list.add);
    String value = Utf8Decoder().convert(list);
    return value;
  }

  /// The string to an int
  static int string2int(String str) {
    return int.parse(str);
  }

  /// The string to a double
  static double string2double(String str) {
    return double.parse(str);
  }

  /// The string to a bool
  static bool string2bool(String str) {
    if (str == 'true') {
      return true;
    } else {
      return false; }}/// Object is converted to string JSON
  static String object2string<T>(T t) {
    return fluroCnParamsEncode(jsonEncode(t));
  }

  /// String JSON to map
  static Map<String.dynamic> string2map(String str) {
    returnjson.decode(fluroCnParamsDecode(str)); }}Copy the code

Page jumpRoutes.push()

Routes.push(context, Routes.addDevice, params: {'gatewayId': gatewayId});
Copy the code

This is the route encapsulation method, just call push.

	/// Hop routing
  /// Path: indicates the routing address
  /// Params: parameter
  /// -Leonard: Transition
  /// Replace: substitution
  static Future push(BuildContext context, String path, {Map<String.dynamic> params, TransitionType transition = TransitionType.cupertino, bool replace = false.bool clearStack = false{})// Encode the parameters to solve the problem that there are special characters in the parameters, which affect the fluro route matching
    String query =  "";
    if(params ! =null) {
      int index = 0;
      for (var key in params.keys) {
        var value = Uri.encodeComponent(params[key]);
        if (index == 0) {
          query = "?";
        } else {
          query = query + \ "&";
        }
        query += "$key=$value"; index++; }}// print('navigateTo pass: $query');

    path = path + query;
    return router.navigateTo(context, path, transition:transition, replace: replace, clearStack: clearStack);
  }
Copy the code

Go back to the previous pageRoutes.pop()

Routes.pop()
Copy the code

Pop method encapsulation

  /// Return to previous page
  static pop() {
    / / the global context
    BuildContext context = navigatorKey.currentState.overlay.context;
    router.pop(context);
  }
Copy the code

So we’re setting a global context, and if we don’t, we just pass the context in.

Such as:

 static pop(BuildContext context) {
   router.pop(context);
 }
Copy the code

Get the global Context

Sometimes, we need to do pop-ups or page jumps in the Web tool class, for example, we need to jump to the login page when there is no login, but the Web tool class is not a Widget, and there is no Context, so we can’t jump to the web tool class. In this case, we need a global Context.

The main file configures the Context

/// Define the global navigatorKey
/// The global context
/// BuildContext context = navigatorKey.currentState.overlay.context;
/// Routing hop
/// navigatorKey.currentState.pushNamed('/');
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

class App extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ATU Smart Home ',
      debugShowCheckedModeBanner: Global.isDebug,
      // Configure the route
      onGenerateRoute: Routes.router.generator,
      // Global configuration
      navigatorKey: navigatorKey,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.primarySwatch: Global.themeColor, ), darkTheme: ThemeData.dark(), home: Root(), ); }}Copy the code

Global Context call

/// The global context
BuildContext context = navigatorKey.currentState.overlay.context;
Copy the code

The resources:

Fluro (pub. Dev/packages/fl…

Flutter – Route Management-02-Fluro (juejin.cn/post/684490…)