Flutter路由管理插件appwrouter_dart的使用

Flutter路由管理插件appwrouter_dart的使用

概述

Appwrouter 是一个为 Appwrite Cloud Functions 设计的简单路由管理器。它可以帮助你创建一个带有中间件支持和错误处理功能的基本路由系统。

什么是 Appwrouter?

Appwrouter 是一个简单的路由管理工具,适用于 Appwrite Cloud Functions。它能够帮助你构建一个基本的路由系统,并且支持中间件和错误处理功能。

为什么使用 Appwrouter?

Appwrite Cloud Functions 缺乏内置的路由系统。通过使用 Appwrouter,你可以轻松地为你的云函数设置路由逻辑。此外,Appwrite Cloud Functions 不支持路径参数(例如 /user/:id),而 Appwrouter 可以很好地解决这个问题。

特性

  • 健壮的路由系统
  • 中间件支持
  • 错误处理
  • 易于使用
  • 路径参数支持
  • 重定向功能
  • 路由版本控制

安装

在项目中添加 Appwrouter 插件:

dart pub add appwrouter

使用示例

1. 创建路由实例并注册路由

首先,创建一个 Appwrouter 实例,并通过 getpostputpatchdelete 方法注册路由。

import 'package:appwrouter_dart/appwrouter_dart.dart';

// 创建路由实例
final router = Appwrouter.instance
  ..get(
    version: "v1",
    path: "/index",
    handler: indexHandler,
  )
  ..get(
    version: "v1",
    path: "/index/:studentId/grades/:id",
    handler: withParamsHandler,
  );

2. 初始化 Appwrouter

在 Appwrite Cloud Function 的主方法中初始化 Appwrouter。

Future<dynamic> main(final context) async {
  context.log("Initializing Appwrouter");

  return await initialize(
    Initialize(
      req: context.req,
      res: context.res,
      log: context.log,
      error: context.error,
      onMiddleware: (payload) async {
        final OnMiddleware(
          :log,
          :req,
          :triggeredType,
          :path,
          :method,
          :eventType,
          :eventMap,
        ) = payload;

        // 在中间件中可以执行一些操作,比如重定向路径
        if (triggeredType == TriggeredType.http && method == MethodType.get) {
          log('Handling GET request');
        }

        // 确保返回 Appwrite SDK 的 Client 对象
        return client;
      },
      onNext: (req, res, client) async {
        return await router.handleRequest(
          handlerequest: HandleRequest(
            req: req,
            res: res,
            log: context.log,
            error: context.error,
            client: client,
          ),
        );
      },
      onError: (e) {
        context.error(e.toString());
        return context.res.send(
          jsonEncode({"message": "Internal Server Error"}),
          500,
          {"content-type": "application/json"},
        );
      },
    ),
  );
}

Appwrouter 实例化

GET 路由

Appwrouter.instance..get(
  version: "v1",
  path: "/",
  handler: (handleRequest) async {
    handleRequest.res.send("Hello World");
  },
)

POST 路由

Appwrouter.instance..post(
  version: "v1",
  path: "/",
  handler: (handleRequest) async {
    handleRequest.res.send("Hello World");
  },
)

PUT 路由

Appwrouter.instance..put(
  version: "v1",
  path: "/",
  handler: (handleRequest) async {
    handleRequest.res.send("Hello World");
  },
)

PATCH 路由

Appwrouter.instance..patch(
  version: "v1",
  path: "/",
  handler: (handleRequest) async {
    handleRequest.res.send("Hello World");
  },
)

DELETE 路由

Appwrouter.instance..delete(
  version: "v1",
  path: "/",
  handler: (handleRequest) async {
    handleRequest.res.send("Hello World");
  },
)

路由处理函数

路由处理函数接收一个对象,包含以下属性:

  • req: 模拟 Appwrite SDK 的请求对象。
  • res: 模拟 Appwrite SDK 的响应对象。
  • log: 日志对象。
  • error: 错误对象。
  • client: Appwrite SDK 的客户端对象。

推荐将路由处理逻辑封装到独立的函数中:

Future<dynamic> handler(HandleRequest handler) async {
  handler.res.send("Hello World");
}

Appwrouter.instance
  ..get(
    version: "v1",
    path: "/",
    handler: handler,
  )

路由版本控制

可以通过在路由处理器的第一个参数中指定版本号来实现路由版本控制。

Appwrouter.instance
  ..get(
    version: "v1",
    path: "/",
    handler: handler,
  )

中间件

中间件可以在请求到达目标处理程序之前执行某些操作,或者进行重定向。

onMiddleware: (payload) {
  final OnMiddleware(
    :log,
    :req,
    :triggeredType,
    :path,
    :method,
    :eventType,
    :eventMap,
  ) = payload;

  if (triggeredType == TriggeredType.event && eventType == EventType.create) {
    log('Redirecting to /v2/micro/users');
    redirect(req, path: "/v2/micro/users");
  }

  return client;
}

重定向

可以通过 redirect 方法实现重定向。

redirect(req, path: "/v1/some/other/path");

路径参数

可以通过 req.params 处理路径参数。

Appwrouter.instance..get(
  version: "/user/:id",
  path: "/",
  handler: (handleRequest) async {
    final HandleRequest(
      :req,
      :res,
      :error,
      :log,
    ) = handleRequest;
    final params = req.params;
    res.send("User ID: ${params["id"]}");
  },
)

更多关于Flutter路由管理插件appwrouter_dart的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter路由管理插件appwrouter_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


appwrouter_dart 是一个用于 Flutter 的路由管理插件,它可以帮助开发者更轻松地管理应用程序中的页面导航和路由。以下是如何在 Flutter 项目中使用 appwrouter_dart 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 appwrouter_dart 的依赖:

dependencies:
  flutter:
    sdk: flutter
  appwrouter_dart: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化路由管理器

在你的 main.dart 文件中,初始化 AppwRouter 并定义你的路由。

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

void main() {
  final router = AppwRouter(
    routes: {
      '/': (context) => HomePage(),
      '/about': (context) => AboutPage(),
      '/profile': (context) => ProfilePage(),
    },
  );

  runApp(MyApp(router: router));
}

class MyApp extends StatelessWidget {
  final AppwRouter router;

  MyApp({required this.router});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: router.onGenerateRoute,
      initialRoute: '/',
    );
  }
}

3. 定义页面

定义你的页面组件,例如 HomePageAboutPageProfilePage

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('This is the Home Page'),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/about');
              },
              child: Text('Go to About'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/profile');
              },
              child: Text('Go to Profile'),
            ),
          ],
        ),
      ),
    );
  }
}

class AboutPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('About'),
      ),
      body: Center(
        child: Text('This is the About Page'),
      ),
    );
  }
}

class ProfilePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: Center(
        child: Text('This is the Profile Page'),
      ),
    );
  }
}

4. 导航到不同页面

你可以在你的应用中使用 Navigator.pushNamed 来导航到不同的页面,如上面的 HomePage 示例所示。

Navigator.pushNamed(context, '/about');

5. 传递参数

如果你需要传递参数到目标页面,可以使用 Navigator.pushNamedarguments 参数。

Navigator.pushNamed(
  context,
  '/profile',
  arguments: {'userId': 123},
);

在目标页面中,你可以通过 ModalRoute.of(context)!.settings.arguments 来获取传递的参数。

class ProfilePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    final Map<String, dynamic> args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    final userId = args['userId'];

    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: Center(
        child: Text('User ID: $userId'),
      ),
    );
  }
}
回到顶部