搜索插件、代码仓与 APP 分类

插件详情v3.1.3

routefly

受 NextJS 启发并由 Flutterando 社区创建的基于文件夹的路由管理器。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
509
喜欢数
205
Pub 分数
150

安装插件

flutter pub add routefly

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

RouteFly 是一个基于文件夹的 Flutter 路由管理包,灵感来自 Next.js,旨在简化 Flutter 应用中的导航。它能自动从定义的文件夹结构生成路由,减少样板代码并改善代码组织。由 Flutterando 社区开发,支持所有主要平台,包括 Android、iOS、Web、macOS、Windows 和 Linux。RouteFly 通过无需手动注册路由即可实现直观且可扩展的路由,提升开发人员的生产力。

适合场景

  • 从文件夹结构自动生成路线
  • 简化大型 Flutter 应用中的导航
  • 启用路由逻辑的清晰分离
  • 支持多平台 Flutter 项目
  • 在团队环境中简化路线管理

主要特点

  • 基于文件夹的路由定义
  • 自动路线生成
  • 最小化样板
  • 跨平台支持
  • 与Flutterando 生态系统的集成

适合对象

  • 使用基于文件夹的项目结构的开发者
  • 寻求可扩展路由解决方案的团队
  • 旨在减少手动路线设置的项目
  • 熟悉 Next.js 约定的 Flutter 开发人员
  • 针对多个平台的应用

使用建议

  • 需要遵守特定的文件夹命名约定
  • 可能需要为复杂的路由参数进行配置
  • 最适合具有结构化目录布局的项目
  • 与手动路由设置相比,自定义选项有限
  • 依赖 Flutterando 的维护者进行更新

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Routefly

Logo

Routefly is a folder-based route manager inspired by NextJS and created by the Flutterando community. It allows you to automatically create routes in your Flutter app by simply organizing your code files within specific directories. When a file is added to the "pages" directory, it's automatically available as a route. Just add the appropriate folder structure inside the "lib/app" folder.

Example:

Logo

Sponsors

Logo

Installation and Initialization

To get started with Routefly, follow these steps:

  1. Add the Routefly package to your Flutter project:
   flutter pub add routefly
  1. You will need to add the @Main() annotation to the main Widget (usually the one containing MaterialApp or CupertinoApp). After adding the necessary imports and parts, the code will be ready to generate the routes.

It is also necessary to use Navigator 2.0, accessed through the MaterialApp.router or CupertinoApp.router constructor, adding the custom routerConfig from Routefly:

// file: my_app.dart

import 'package:routefly/routefly.dart';
import 'my_app.route.dart'; // <- GENERATED

part 'my_app.g.dart'; // <- GENERATED

@Main('lib/app')
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: Routefly.routerConfig(
        routes: routes, // GENERATED
      ),
    );
  }
}

The @Main() takes a parameter for the folder that will be used by Routefly as the base to look for pages. The default base folder is lib/app;

  1. Organize your code by creating folders that contain a *_page.dart file for each page. For example:
.
└── app/
    ├── product/
    │   └── product_page.dart
    └── user/
        └── user_page.dart
  1. Generate routes using the following command:
dart run routefly

Run this command every time you create a new folder with a page to generate the routes again. You can also use the --watch flag to automatically generate routes when adding a new page to a folder.

Route Groups

In the app directory, nested folders are normally mapped to URL paths. However, you can mark a folder as a Route Group to prevent the folder from being included in the route's URL path.

This allows you to organize your route segments and project files into logical groups without affecting the URL path structure.

A route group can be created by wrapping a folder's name in parenthesis: (folderName)

.
└── app/
    ├── (product)/
        └── home/
            └── home_page.dart

Generate => /home;

Navigation

Routefly provides simple navigation methods:

Routefly.navigate('path'): Replaces the entire route stack with the requested path.
Routefly.pushNavigate('path'): Adds a new route on top of the existing stack.
Routefly.push('path'): Adds a route to the route stack.
Routefly.pop(): Removes the top route from the route stack.
Routefly.replace('path'): Replaces the last route in the stack with the requested path.

You can use RELATIVE PATH also;

It is also possible to access routes using Record routePaths which replaces the strings which represent the path by an object notation.

// String notation
Routefly.navigate('/dashboard/users');

// Object Notation
Routefly.navigate(routePaths.dashboard.users);

Dynamic routes are also represented by objects, but it is necessary to replace the dynamic parameters;
Use the changes() method to do this;

// String notation => /product/[id]
Routefly.navigate('/product/1');

// Object Notation => /product/[id]
Routefly.navigate(routePaths.product.changes({'id': '1'}));

Dynamic Routes

Dynamic Routes allow you to create routes from dynamic data. You can use dynamic segments enclosed in brackets, such as [id] or [slugs]. For example:

Create a page using a dynamic segment: lib/app/users/[id]/user_page.dart. This generates the route path /users/[id].

Use navigation commands to replace the dynamic segment, like Routefly.push('/users/2').

Access the dynamic parameter (id) on the page using Routefly.query['id'].

You can also access segment parameters using Routefly.query.params, e.g., Routefly.query.params['search'] for /product?search=Text.

Custom Transition

To create custom route transitions, define a routeBuilder function in your page file. This allows you to use custom transitions based on PageRouteBuilder. For example:

Route routeBuilder(BuildContext context, RouteSettings settings) {
  return PageRouteBuilder(
    settings: settings // <- !! DON'T FORGET THAT !!
    pageBuilder: (_, a1, a2) => const UserPage(),
    transitionsBuilder: (_, a1, a2, child) {
      return FadeTransition(opacity: a1, child: child);
    },
  );
}

It is also possible to change the global transition of the routes:

@override
  Widget build(BuildContext context) {
    return CupertinoApp.router(
      routerConfig: Routefly.routerConfig(
        routes: routes,
        routeBuilder: (context, settings, child) {
          return CupertinoPageRoute(
            settings: settings, // !! IMPORTANT !!
            builder: (context) => child,
          );
        },
      ),
    );
  }

Layout (RouterOutlet)

Layout are pages that support nested navigation. All child routes to the layout will be pointed out as children in the navigation.

.
└── app/
    └── dashboard/
        ├── users/
        │   └── users_page.dart
        ├── products/
        │   └── products_page.dart
        └── dashboard_layout.dart

To create a layout, create the folder it will belong to and add a *_layout.dart file. The child folders must be inside the layout's parent folder.

In the Layout Widget, add RouterOutlet() wherever you prefer nested routes to appear. ex:

RouterOutlet(),

Tip

If the error occurs:
EXCEPTION CAUGHT BY RENDERING LIBRARY
The following assertion was thrown during performResize().

This error usually occurs in lists, columns and rows when an element does not have a defined size. To fix it, you can use, for example, Expanded, Center or SizedBox. In this example, I chose to use Expanded.

class DashboardLayout extends StatelessWidget {
  const DashboardLayout({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            ListTile(
              title: const Text('Option 1'),
              onTap: () {
                Routefly.navigate(routePaths.dashboard.products);
              },
            ),
            ListTile(
              title: const Text('Option 2'),
              onTap: () {
                Routefly.navigate(routePaths.dashboard.users);
              },
            ),
            const Expanded(child: RouterOutlet()),
          ],
        ),
      ),
    );
  }
}

Logo

Middleware

Middleware are functions that intercept the request and can change the route information and can cancel or redirect the route request.

FutureOr<RouteInformation> _guardRoute(RouteInformation routeInformation) {
  if (routeInformation.uri.path == '/guarded') {
    return routeInformation.redirect(Uri.parse('/'));
  }

  return routeInformation;
}

Now add it to the initial configuration.

return MaterialApp.router(
      routerConfig: Routefly.routerConfig(
        routes: routes,
        middlewares: [_guardRoute], // <<<<
      ),
    );

Not found page (404)

When creating a route with name 404, it will be triggered when a page is not found. Routefly gives the possibility to modify the default route for unfound pages.

return MaterialApp.router(
      routerConfig: Routefly.routerConfig(
        routes: routes,
        notFoundPath: '/not-found',
      ),
    );

Logo

If you have any questions or need assistance with the package, feel free to reach out to the Flutterando community.

Happy routing with Routefly!

所属分类

依赖

依赖清单 2 项

源码仓库

使用此插件的项目