Javascript is required
Flutter-GetX

GetX-路由管理

GetX 是 Flutter 上的一个轻量且强大的解决方案:高性能的状态管理、智能的依赖注入和便捷的路由管理

9293619FAE5BB8612F2740B0984FD9BF

安装

pubspec.yaml

...
dependencies:
  flutter:
    sdk: flutter
  ...
  get: ^3.17.1 # Add
  ...

引入

import 'package:get/get.dart';

如果你想免上下文(context)使用路由/snackbars/dialogs/bottomsheets,GetX对你来说也是极好的

在你的MaterialApp前加上 "Get",把它变成GetMaterialApp。

GetMaterialApp( // Before: MaterialApp(
  home: MyHome(),
)

例子

普通路由导航

导航到新页面

Get.to(NextScreen());

要关闭snackbars, dialogs, bottomsheets或任何你通常会用Navigator.pop(context)关闭的东西。

Get.back();

进入下一个页面,但没有返回上一个页面的选项(用于闪屏页,登录页面等)。

Get.off(NextScreen());

进入下一个页面并取消之前的所有路由(在购物车、投票和测试中很有用)。

Get.offAll(NextScreen());

在另一个页面上,发送前一个路由的数据。

携带返回值返回

Get.back(result: 'success');

接受

CheetahButton('arguments命名路由', () async {
  var result = await Get.toNamed(Routes.NAV_SIMPLE, arguments: '小叮当');
  print('带参数命名路由返回:$result');
}),

这个arguments通过

final String argName = Get.arguments; // 接收

params命名路由

路由带参数 类似于前端get请求的params

CheetahButton(
  'params命名路由',
  () => Get.toNamed('${Routes.NAV_SIMPLE}?name=Taoya&age=22'),
),

接收

class NavSimplePage extends StatelessWidget {
  final String name = Get.parameters['name'];
  final String age = Get.parameters['age'];
  ......
}

path命名路由

类似于前端的位置参数

比如

/book/1

/book/2

...

定义

GetPage(
      name: "${Routes.NAV_SIMPLE}/:name",
      page: () => NavSimplePage(),
),
...
...
CheetahButton(
  'path命名路由',
  () => Get.toNamed('${Routes.NAV_SIMPLE}/taoya'),
),

使用

/// 进入新页面打印参数
print(Get.parameters);  // I/flutter ( 4292): {name: taoya}

replace路由

浏览并删除前一个页面。

定义

CheetahButton('replace路由', () {
  Get.offNamed(Routes.NAV_SIMPLE);
}),

原生Flutter路由

只要把 Navigator(大写)改成 navigator(小写),你就可以拥有标准导航的所有功能,而不需要使用context

例如:

// 默认的Flutter导航
Navigator.of(context).push(
  context,
  MaterialPageRoute(
    builder: (BuildContext context) {
      return HomePage();
    },
  ),
);

// 使用Flutter语法获得,而不需要context。
navigator.push(
  MaterialPageRoute(
    builder: (_) {
      return HomePage();
    },
  ),
);

// get语法 (这要好得多)
Get.to(HomePage());

别名路由导航

导航到下一个页面

Get.toNamed("/NextScreen");

浏览并删除前一个页面。

Get.offNamed("/NextScreen");

浏览并删除所有以前的页面。

Get.offAllNamed("/NextScreen");

要定义路由,使用GetMaterialApp。

void main() {
  runApp(
    GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => MyHomePage()),
        GetPage(name: '/second', page: () => Second()),
        GetPage(
          name: '/third',
          page: () => Third(),
          transition: Transition.zoom  
        ),
      ],
    )
  );
}

这样优点臃肿. 创建一个文件

app_pages.dart

// 页面
import 'package:demo_getx/modules/home/home_page.dart';
import 'package:demo_getx/modules/nav/nav_page.dart';
import 'package:demo_getx/modules/nav/simple_page.dart';
// 插件
import 'package:get/get.dart';
// 自定义路由表
part './app_routes.dart';

abstract class AppPages {
  static final pages = [
    GetPage(
      name: Routes.HOME,
      page: () => HomePage(),
    ),
    GetPage(
      name: Routes.NAV,
      page: () => NavPage(),
    ),
    GetPage(
      name: Routes.NAV_SIMPLE,
      page: () => NavSimplePage(),
    ),
    GetPage(
      name: "${Routes.NAV_SIMPLE}/:name",
      page: () => NavSimplePage(),
    ),
  ];
}

定义路由表

routes/app_routers.dart

abstract class Routes {
  static const INITIAL = '/'; // 初始化
  static const HOME = '/home'; // 首页
  static const NAV = '/nav'; // 导航
  // ...
}

使用

onTap: () {
  print("点击了路由'");
  Get.toNamed(Routes.NAV);
}

定制404页面

处理未找到的路由

可以在GetMaterialApp中定义unknownRoute页面。

void main() {
  runApp(
    GetMaterialApp(
      unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => MyHomePage()),
        GetPage(name: '/second', page: () => Second()),
      ],
    )
  );
}

免context导航

用Flutter创建一个简单的SnackBar,你必须获得Scaffold的context,或者你必须使用一个GlobalKey附加到你的Scaffold上。

final snackBar = SnackBar(
  content: Text('Hi!'),
  action: SnackBarAction(
    label: 'I am a old and ugly snackbar :(',
    onPressed: (){}
  ),
);
// 在小组件树中找到脚手架并使用它显示一个SnackBars。
Scaffold.of(context).showSnackBar(snackBar);

使用GetX

Get.snackbar('Hi', 'i am a modern snackbar');

更多参数

Get.snackbar(
  "Hey i'm a Get SnackBar!", // title
  "It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!", // message
  icon: Icon(Icons.alarm),
  shouldIconPulse: true,
  onTap:(){},
  barBlur: 20,
  isDismissible: true,
  duration: Duration(seconds: 3),
);


  ////////// ALL FEATURES //////////
  //     Color colorText,
  //     Duration duration,
  //     SnackPosition snackPosition,
  //     Widget titleText,
  //     Widget messageText,
  //     bool instantInit,
  //     Widget icon,
  //     bool shouldIconPulse,
  //     double maxWidth,
  //     EdgeInsets margin,
  //     EdgeInsets padding,
  //     double borderRadius,
  //     Color borderColor,
  //     double borderWidth,
  //     Color backgroundColor,
  //     Color leftBarIndicatorColor,
  //     List<BoxShadow> boxShadows,
  //     Gradient backgroundGradient,
  //     FlatButton mainButton,
  //     OnTap onTap,
  //     bool isDismissible,
  //     bool showProgressIndicator,
  //     AnimationController progressIndicatorController,
  //     Color progressIndicatorBackgroundColor,
  //     Animation<Color> progressIndicatorValueColor,
  //     SnackStyle snackStyle,
  //     Curve forwardAnimationCurve,
  //     Curve reverseAnimationCurve,
  //     Duration animationDuration,
  //     double barBlur,
  //     double overlayBlur,
  //     Color overlayColor,
  //     Form userInputForm
  ///////////////////////////////////

参考

https://github.com/jonataslaw/getx/blob/master/documentation/zh_CN/route_management.md#navigation-with-named-routes