Flutter’s super easy-to-use routing library-fluro

Please add image description

Introduction to fluro

Introduction to fluro

fluro is a popular Flutter plug-in for advanced routing management. It provides flexible route configuration and navigation functions and supports named routes, parameter passing, route interception, animation effects, etc., making it easier and scalable to manage page navigation in Flutter applications. The following is a detailed introduction to the fluro plug-in:

Install and import

You can install the fluro plugin by adding the fluro dependency in the pubspec.yaml file.

fluro: ^2.0.5

Then, in the files that need to use fluro, import import 'package:fluro/fluro.dart';the library.

Routing configuration

Using fluro, you configure routing by creating a FluroRouter instance. By calling the define method, you can specify a unique route name for each page and associate a handler (Handler).

final router = FluroRouter();
router.define('/home', handler: Handler(handlerFunc: (context, parameters) => HomeScreen()));
router.define('/profile/:id', handler: Handler(handlerFunc: (context, parameters) {
    
    
  final id = parameters['id']?.first;
  return ProfileScreen(userId: id);
}));

The sample code above demonstrates how to use definemethods to configure routing for HomeScreenand ProfileScreenpages. In the second route, :idrepresents a parameter that can be passed in the route and used in the handler.

Navigate to route

Using fluro, you can navigate to a configured named route using the router.navigateTo method. You can pass parameters when navigating and specify transition animations for navigation.

router.navigateTo(context, '/home');
router.navigateTo(context, '/profile/123', transition: TransitionType.fadeIn);

In the example above, we navigate to named routes for /homeand respectively. Specifies the transition animation effect during navigation./profile/123TransitionType.fadeIn

Parameter passing

fluro supports passing parameters in routes, and parameters can be obtained and used in handlers. You can use the RouteParams class to access route parameters.

router.define('/profile/:id', handler: Handler(handlerFunc: (context, parameters) {
    
    
  final id = parameters['id']?.first;
  return ProfileScreen(userId: id);
}));

In the above example, :idrepresents a parameter that can be passed in the route. In the handler we use parametersparameters to get the route parameters and pass them to ProfileScreen.

Route Interceptors:
Fluro allows you to add route interceptors to perform some action before navigating to a specific route. Interceptors can be used for authentication, permission checking, etc.

final authMiddleware = FluroMiddleware();
authMiddleware.handler = (context, parameters) async {
    
    
  if (!AuthService.isLoggedIn) {
    
    
    router.navigateTo(context, '/login', replace: true);
  }
};

router.define('/profile/:id', handler: Handler(handlerFunc: (context, parameters) {
    
    
  final id = parameters['id']?.first;
  return ProfileScreen(userId: id);
}), middleware: [authMiddleware]);

In the above example, we create a route interceptor and apply it to /profile/:idthe route. If the user is not logged in, the interceptor navigates to the login page.

Animation effects:
fluro supports applying custom transition animation effects during route navigation. You can use various transition animation effects provided by the TransitionType enumeration, such as TransitionType.fadeIn, TransitionType.cupertino, etc.

router.navigateTo(context, '/profile/123', transition: TransitionType.fadeIn);

In the above example, we will navigate to the `/profile/123 route and specify the transition animation effect to fadeIn.

Typical uses of fluro

When using the Fluro library, you can initialize and implement global routing management through the following steps:

Create routing management class

Create a single routing management class in the project to manage and process routing-related operations.


import 'package:fluro/fluro.dart';

class AppRouter {
    
    
  static final AppRouter _instance = AppRouter._internal();

  factory AppRouter() {
    
    
    return _instance;
  }

  AppRouter._internal();

  static FluroRouter router = FluroRouter();

  // 添加路由处理方法
  void defineRoutes() {
    
    
    router.define('/home', handler: homeHandler);
    // 定义其他路由...
  }

  // 定义路由处理器
  final homeHandler = Handler(
    handlerFunc: (BuildContext? context, Map<String, dynamic> params) {
    
    
      return HomePage();
    },
  );
}

In the above example, we created a AppRouterroute management class called which defines an FluroRouterinstance and a series of route processing methods. Within defineRoutesmethods, we can use router.definemethods to define routes and corresponding handlers.

Code explanation

The example uses the singleton pattern to ensure that only one instance is created in the entire application, and when multiple pages introduce this class, it is guaranteed to call the same instance.

Let us explain the meaning of this code in detail:

static keyword:
static` keyword modification, which means that the member does not depend on the instance of the class and can be accessed directly through the class name.

final keyword:
The final keyword is used to declare a variable that can only be assigned once. Here, _instance is declared as final`, which means that it cannot be modified after being assigned.

AppRouter type:
_instance is a variable of AppRouter type, which is used to store the only instance of the AppRouter` class.

Private constructor named by _internal():
_internal is the name of a private constructor, which cannot be called directly from the outside. This means that instances of AppRouter` cannot be created elsewhere via AppRouter._internal().

Implementation of singleton pattern:
Here, _instance is declared as static final, and the private constructor is called through AppRouter._internal() at the time of declaration to create the only instance. Since private constructors cannot be called externally, instances can only be created inside the class.

Example summary

By making the constructor private, using a static final variable to store the unique instance, and accessing the instance through static methods, the code ensures that only one AppRouter instance is created throughout the application. When multiple pages introduce this class, you can obtain the same instance through AppRouter() to ensure that the same instance is called. This conforms to the concept of the singleton pattern and implements a globally shared routing manager.

Initialize routing

At the entry point of the application, usually in the main.dart file, the routing is initialized and configured.

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

void main() {
    
    
  // 初始化路由
  FluroRouter router = AppRouter.router;
  AppRouter().defineRoutes();

  // 启动应用程序
  runApp(MyApp());
}

In the above example, we first AppRouter.routerget FluroRouterthe instance via and then call defineRoutesthe method to define the route. This completes the routing initialization and configuration.

Navigate to route

Where you need to navigate to a route, you can use a FluroRouter instance to perform route navigation operations.

AppRouter.router.navigateTo(context, '/home');

In the above example, we use navigateTomethods to navigate to '/home'routes. Parameters can be passed according to actual needs.
Through the above steps, we can use AppRouter.router throughout the application to access the global routing manager. This way we can perform route navigation and management operations anywhere without explicitly passing an instance of the route manager.

Please note that the above examples are for demonstration purposes only and do not involve complete Fluro configuration and usage. In actual development, it is also necessary to configure routing interceptors, pass parameters, handle dynamic routing, etc. according to specific needs. You can refer to the official documentation and sample code of the Fluro library for more detailed usage instructions and examples.

Summarize

By using the fluro plugin, you can more easily configure and manage routing in your Flutter application. It provides flexible route configuration methods, parameter transfer, route interception, animation effects and other functions, making application navigation management simpler and more scalable. Whether building small to medium-sized applications or large-scale applications, fluro is a powerful and popular choice.

Guess you like

Origin blog.csdn.net/yikezhuixun/article/details/133066289