router_generator 0.1.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 51

router_generator #

router_generator 是用于flutter路由的页面表及页面参数绑定自动生成框架 #

安装 #

dev_dependencies:
  router_generator: 0.1.1
  build_runner:

引用 #

import 'package:router_generator/router_generator.dart';

页面标记 #

@Router('third')
class ThirdPage extends StatefulWidget {

在页面Widget上使用Router注解,页面名作为参数

参数标记 #

@inject
class ThirdPageState extends State<ThirdPage> {
  @RouterParam(required: true)
  Person person;
  @RouterParam(key: 'set_key')
  bool setKey = false;
  @routerParam
  Map<String, int> map;

给需要注入依赖的State添加inject注解,并且在变量上添加RouterParam 注解RouterParam有两个可选的参数:

  • key: 此参数在参数表中的键,默认用变量名
  • required:是否必须,如果是的话,在依赖注入时,如果参数表中没有此参数,debug模式下会报错,并且在生成的createRouteArgs方法中此参数为必须。

如果两个参数都不需要,建议用routerParam注解。 从例子中可以看到,dart的各种类型包括自定义的model都是支持的

代码生成 #

执行命令:flutter packages pub run build_runner build, 更多使用方法可参考 build_runner

生成的若干dart文件中包含:

  • 页面路由表 main.router_table.dart
  • 页面依赖注入 $page.inject.dart 若干个,其中 page 是你 state所在 文件的名称,例如 foo.dart对应foo.inject.dart

引用 #

路由生成

MaterialApp(
  ...
  onGenerateRoute: (RouteSettings settings) {
    String pageName = settings.name;
    var arguments = settings.arguments;
    if (arguments is Map<String, dynamic>) {
      deliverParams(pageName, arguments);
    }
    return MaterialPageRoute(builder: (_) {
      return getWidgetByPageName(pageName);
    });
  },
);

修改onGenerateRoute方法,调用main.router_table.dart中的getWidgetByPageName,获取对应的页面Widget,并且deliverParams()传递参数。

对于嵌入原有原生的App,可参考:

onGenerateRoute: (RouteSettings settings) {
    String route = settings.name;
    Uri uri = Uri.parse(route);
    var pageName = uri.path.replaceFirst(RegExp('/'), '');
    lastRouteParams = uri.queryParameters;
    return PageRouteBuilder(pageBuilder: (BuildContext context,
        Animation<double> animation, Animation<double> secondaryAnimation) {
      return getWidgetByPageName(pageName);
    });
  },

Map<String, String>类型的参数表(即uri中值为字符串的参数表)也是支持的,不需要额外转换。

依赖注入

在已注入依赖的state中import 对应的inject文件,在使用变量前注入依赖,如:

@override
void initState() {
	super.initState();
	injectDependencies(this);
	doSometing();
}

传递依赖


Navigator.of(context).pushNamed('second',
                    arguments: {'name': 'bar', 'count': 666});
                    

可以手动创建依赖的参数表,但建议使用 inject 文件中的 createRouteArgs方法。

Navigator.of(context).pushNamed('second',
                    arguments: createRouteArgs(name: 'bar', count: 666));

0.1.0 #

Feature #

  • Code generation for router widget binding and params binding

0.1.1 #

Fix #

  • Optimized code, avoid unnecessary codes

example/lib/main.dart

import 'package:example/router.router_table.dart';
import 'package:example/model.dart';
import 'package:example/second_page.inject.dart';
import 'package:example/third_page.inject.dart' as third_page;
import 'package:flutter/material.dart';
import 'package:router_generator/router_generator.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      onGenerateRoute: (RouteSettings settings) {
        String pageName = settings.name;
        var arguments = settings.arguments;
        if (arguments is Map<String, dynamic>) {
          deliverParams(pageName, arguments);
        }
        return MaterialPageRoute(builder: (_) {
          return getWidgetByPageName(pageName);
        });
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text('Router Generator'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            InkWell(
              child: Text(
                'second page',
                style: TextStyle(fontSize: 20),
              ),
              onTap: () {
                Navigator.of(context).pushNamed('second',
                    arguments: createRouteArgs(name: 'bar'));
              },
            ),
            InkWell(
              child: Text('third page', style: TextStyle(fontSize: 20)),
              onTap: () {
                Navigator.of(context).pushNamed('third',
                    arguments: third_page.createRouteArgs(Person(23, 'kobe')));
              },
            ),
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  router_generator: ^0.1.2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:router_generator/router_generator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
2
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
51
Learn more about scoring.

We analyzed this package on Apr 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
source_gen ^0.9.4+7 0.9.5
Transitive dependencies
_fe_analyzer_shared 2.1.0
analyzer 0.39.6
args 1.6.0
async 2.4.1
build 1.2.2
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
csslib 0.16.1
dart_style 1.3.4
glob 1.2.0
html 0.14.0+3
js 0.6.1+1
logging 0.11.4
meta 1.1.8
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.9.3
path 1.6.4
pedantic 1.9.0
pub_semver 1.4.4
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+14
yaml 2.2.0