Flutter路由宏定义插件shelf_router_macro的使用

Flutter路由宏定义插件shelf_router_macro的使用

构建状态 发布版本 许可证:MIT

🚧 实验性支持 用于 shelf_router 的宏定义。

🌟 特点

  • ✨ 路由声明
  • ✨ 路由参数
  • ✨ 异步路由
  • ✨ 轻量级 - 无需额外依赖,只需 shelf_router
  • 🖊️ 开发中 直观 - 自定义返回类型
  • 🖊️ 开发中 简洁 - 无需指定 Request/Response,直接返回响应体

🧑‍💻 示例

import 'package:data_class_macro/data_class_macro.dart';

[@Controller](/user/Controller)()
class GreetingController {
  [@Get](/user/Get)('/wave')
  Future<String> wave() async {
    await Future.delayed(const Duration(seconds: 1));
    return '_o/';
  }
}
import 'package:json/json.dart';
import 'package:data_class_macro/data_class_macro.dart';

@JsonCodable()
class Pong {
  Pong({required this.uid});

  final String uid;
}

[@Controller](/user/Controller)()
class PingController {
  [@Get](/user/Get)('/ping/<uid>')
  Future<Pong> ping(String uid) async {
    return Pong(uid: uid);
  }
}

🚀 快速开始

重要

此包需要 Dart SDK >= 3.5.0-164.0.dev

1. 下载 Dart 来自 `dev` 或 `master` 渠道 - [Dart SDK 归档](https://dart.dev/get-dart/archive#dev-channel) - [dvm: Dart 版本管理器](https://github.com/cbracken/dvm) - 或者,您可以简单地切换到 flutter master 渠道: ```sh $ flutter channel master ```
  1. 在你的 <code>pubspec.yaml</code> 中添加 <code>package:shelf_router_macro</code>

    $ dart pub add shelf_router_macro
    
  2. <code>analysis_options.yaml</code> 中启用实验性宏

    analyzer:
      enable-experiment:
        - macros
    
  3. 使用此库提供的注解(见上述示例)。

  4. 运行它

    $ dart --enable-experiment=macros run lib/main.dart
    

🙌 手把手指南

定义路由

所有路由应作为带有 <code>[@Controller](/user/Controller)()</code> 注解的类的一部分进行声明:

[@Controller](/user/Controller)()
class SomeController {
  [@Get](/user/Get)('/')
  String health() => 'ok';
}

自定义响应

返回 shelf 的 <a href="https://pub.dev/documentation/shelf/latest/shelf/Response-class.html">Response</a>

[@Get](/user/Get)('/')
String health() => Response.ok(
      'ok',
      headers: {'X-Test': 'test'},
    );

访问请求详情

在方法签名中包含 shelf 的 <a href="https://pub.dev/documentation/shelf/latest/shelf/Request-class.html">Request</a>

[@Get](/user/Get)('/')
String test(Request r) => 'Headers: ${r.headers}';

示例代码

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router_macro/shelf_router_macro.dart';

[@Controller](/user/Controller)()
class GreetingController {
  [@Get](/user/Get)('/')
  Response greeting(Request request) {
    return Response.ok('Hello, world!');
  }

  [@Get](/user/Get)('/<name>')
  String greetingByName(String name) {
    return 'Hello, $name!';
  }

  [@Get](/user/Get)('/wave')
  Future<String> asyncWave() async {
    await Future.delayed(const Duration(seconds: 1));
    return '_o/';
  }
}

const host = 'localhost';
const port = 8080;

void main() async {
  final controller = GreetingController();
  unawaited(
    serve(controller.router, host, port),
  );

  print('🔍 Testing...\n');
  await HttpClient().get(host, port, '/').sendAndLog();
  await HttpClient().get(host, port, '/eeqk').sendAndLog();
  await HttpClient().get(host, port, '/wave').sendAndLog();

  print('\n');
  print('✅ Server is running at http://$host:$port/');
}

extension SendRequestExt on Future<HttpClientRequest> {
  Future<void> sendAndLog() async {
    final request = await this;
    final response = await request.close();

    print('📡 Request: ${request.method} ${request.uri}');
    print('${response.statusCode} ${response.reasonPhrase}');
    print(await response.transform(utf8.decoder).join());
  }
}

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

1 回复

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


当然,以下是一个关于如何使用 shelf_router_macro 插件在 Flutter 项目中进行路由宏定义的示例代码。需要注意的是,shelf_router_macro 并不是 Flutter 官方或广泛使用的插件,这里假设它是一个用于生成路由配置的 Dart 宏插件。由于实际插件的 API 和功能可能有所不同,以下代码仅为示例,具体使用时请参考该插件的官方文档。

首先,确保你的 pubspec.yaml 文件中包含了对 shelf_router_macro 的依赖(这里仅为假设名称,实际使用时请替换为真实插件名称):

dependencies:
  flutter:
    sdk: flutter
  shelf_router_macro: ^x.y.z  # 替换为实际版本号

dev_dependencies:
  build_runner: ^x.y.z  # 用于运行构建脚本

然后,你可以按照以下步骤使用宏定义路由:

  1. 定义路由宏

    创建一个新的 Dart 文件,例如 router.dart,用于定义路由宏。

    import 'package:shelf_router_macro/shelf_router_macro.dart';
    
    [@RouterMacro](/user/RouterMacro)()
    class MyRoutes {
      static const String home = '/home';
      static const String details = '/details/:id';
    }
    
  2. 生成路由配置

    使用 build_runner 来生成路由配置代码。在命令行中运行以下命令:

    flutter pub run build_runner build
    

    这应该会生成一个包含路由配置的文件,例如 router_config.g.dart

  3. 使用生成的路由配置

    在你的 Flutter 应用中使用生成的路由配置。假设生成的配置文件名为 router_config.g.dart,你可以这样使用它:

    import 'package:flutter/material.dart';
    import 'router_config.g.dart' as generatedRoutes; // 导入生成的路由配置
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          initialRoute: generatedRoutes.MyRoutes.home, // 使用生成的初始路由
          routes: generatedRoutes.routes, // 使用生成的路由表
        );
      }
    }
    
    // 示例页面
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Home Page'),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, generatedRoutes.MyRoutes.details, arguments: {'id': '123'});
              },
              child: Text('Go to Details'),
            ),
          ),
        );
      }
    }
    
    class DetailsPage extends StatelessWidget {
      final Map<String, dynamic> args;
    
      DetailsPage({required this.args});
    
      @override
      Widget build(BuildContext context) {
        final id = args['id'] as String;
        return Scaffold(
          appBar: AppBar(
            title: Text('Details Page'),
          ),
          body: Center(
            child: Text('Details for ID: $id'),
          ),
        );
      }
    }
    

    在上面的代码中,generatedRoutes.routes 是一个由宏生成的路由表,generatedRoutes.MyRoutes.homegeneratedRoutes.MyRoutes.details 是宏定义的路由路径。

请注意,由于 shelf_router_macro 并非真实存在的插件,上述代码仅为示例。实际使用时,你需要根据所使用插件的文档进行相应调整。如果你正在寻找一个实际的 Flutter 路由管理解决方案,可以考虑使用 flutter_navigatorflutter_hooks 等流行插件。

回到顶部