Flutter路由生成插件getx_route_generator_q1的使用

Flutter路由生成插件getx_route_generator_q1的使用

getx_route_generator_q1 是一个基于 build_runner 的代码生成库,旨在为使用 GetX 库的页面生成路由表。告别手动编写路由路径和 GetPage 映射。

新特性

你可以在 pubspec.yaml 文件中启用静态模型:

...
getx_route_generator_q1:
  static_to_page: true

flutter:
  uses-material-design: true
...

这将生成静态的 toPage 方法扩展,例如:

extension ChatVideoPreviewPageToPage on ChatVideoPreviewPage {
  static Future<void>? toPage({
    required final String userId,
    required final CallType callType,
    required final bool isFree,
    final CallChannel? channel,
    final bool preventDuplicates = true,
    int? id,
  }) {
    return Get.toNamed<void>(
      RouteTable.chatVideoPreviewPage,
      preventDuplicates: preventDuplicates,
      id: id,
      arguments: {
        'userId': userId,
        'callType': callType,
        'isFree': isFree,
        'channel': channel,
      },
    );
  }

  static Future<void>? offAndToPage({
    required final String userId,
    required final CallType callType,
    required final bool isFree,
    final CallChannel? channel,
    int? id,
  }) {
    return Get.offAndToNamed<void>(
      RouteTable.chatVideoPreviewPage,
      id: id,
      arguments: {
        'userId': userId,
        'callType': callType,
        'isFree': isFree,
        'channel': channel,
      },
    );
  }
}

使用方法

dependenciesdev_dependencies 中添加最新版本的 getx_route_generator_q1

dependencies: 
  getx_route_annotations_q1: [latest-version]

dev_dependencies:                    
  getx_route_generator_q1: [latest-version]

在特定路由页面类上添加 GetXRoutePage 注解:

@GetXRoutePage("/home")
class HomePage extends StatefulWidget {}

(注意:GetXRoutePage 需要传递路径。在生成的路由表类中,会自动生成类似以下的全局变量,并可以直接使用。)

static const String home = '/home';

然后在终端运行以下命令:

flutter pub run build_runner build

getx_route_generator_q1 将根据你添加的注解自动在 lib/generated 目录下生成 route_table.dart 文件。生成的代码如下:

import 'package:get/get.dart';
import 'package:xxx/page/home_page.dart';

class RouteTable {
  static const String home = '/home';

  static final List<GetPage> pages = [
    GetPage(name: '/home', page: () => HomePage()),
  ];
}

当然,你也可以使用 watch 命令,这样每次修改路由页面时就不必重新运行构建命令:

flutter pub run build_runner watch

绑定

如果你需要为 GetPage 添加绑定,可以使用以下方法添加所需的控制器或对象。在 GetXRoutePage 注解中添加 dependencies 参数,并传递数组:

@GetXRoutePage("/home", dependencies:[XController, XXController, XXXController])
class HomePage extends StatefulWidget {}

生成的代码如下:

class RouteTable {
  static const String home = '/home';

  static final List<GetPage> pages = [
    GetPage(
      name: '/home',
      page: () => HomePage(),
      binding: BindingsBuilder(() {
        Get.lazyPut<XController>(() => XController());
        Get.lazyPut<XXController>(() => XXController());
        Get.lazyPut<XXXController>(() => XXXController());
      }),
    ),
  ];
}

就是这样!


示例代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

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

1 回复

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


getx_route_generator_q1 是一个用于 Flutter 项目中自动生成 GetX 路由的插件。它可以帮助开发者简化路由管理,减少手动编写路由代码的工作量。以下是如何使用 getx_route_generator_q1 插件的详细步骤:

1. 安装插件

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

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5  # 确保你已经安装了 GetX

dev_dependencies:
  build_runner: ^2.1.11
  getx_route_generator_q1: ^1.0.0  # 添加插件依赖

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

2. 创建路由注解

在你的 Flutter 项目中,创建一个 routes.dart 文件(或者你喜欢的其他名字),并在其中定义你的页面路由。使用 @GetXRoute 注解来标记每个页面。

import 'package:getx_route_generator_q1/getx_route_generator_q1.dart';

part 'routes.g.dart';  // 自动生成的路由文件

@GetXRoute(name: '/home', page: HomePage)
class HomeRoute {}

@GetXRoute(name: '/profile', page: ProfilePage)
class ProfileRoute {}

@GetXRoute(name: '/settings', page: SettingsPage)
class SettingsRoute {}

3. 生成路由代码

在终端中运行以下命令来生成路由代码:

flutter pub run build_runner build

这将生成一个 routes.g.dart 文件,其中包含所有自动生成的路由代码。

4. 使用生成的路由

main.dart 或你的主文件中,使用生成的路由来配置 GetX 路由。

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'routes.dart';  // 导入生成的路由文件

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/home',
      getPages: AppRoutes.routes,  // 使用生成的路由
    );
  }
}

5. 导航到页面

你可以使用 GetX 提供的导航方法来跳转到不同的页面:

Get.toNamed('/profile');  // 跳转到 Profile 页面
Get.offNamed('/settings');  // 跳转到 Settings 页面并关闭当前页面
回到顶部