I used GetX to write a use demo, and an app, the demo navigation demonstration is as follows:

Code sample

preface

GetX is a lightweight and powerful solution for Flutter: high-performance state management, intelligent dependency injection, and convenient route management.

Why GetX, not BLoC, MobX, Provider?

BLoC is very safe and efficient, but it is very complicated for beginners, and even if they learn it, there is a lot of boilerplate code.

MobX is easier than BLoC and responsive, but requires the use of a code generator and a long wait, which reduces productivity.

GetX what I like about:

  • Light weight. Modules are compiled separately and unused functions are not compiled into our code.
  • Syntax concise. I really like it, it’s obvious and it’s practical, like routing without context,Get.to(SomePage())We can navigate to the new route.
  • Performance. Provider, BLoC, etc., can only save state in parent and child components. State management of modules at the same level needs to be handled globally and can survive in the entire application life cycle. GetX, on the other hand, can add and remove controllers at any time, and will automatically release used controllers.
  • Dependency injection. Providing dependency injection, the code hierarchy can be completely separated, even the dependency injection code is separated.
  • Rich API. Many complex operations can be easily implemented using GetX.

Some students have read my article about the use and encapsulation of the Flutter state management provider and explained how to use the provider. In fact, many pain points have been found in the process of using the Flutter state management provider. The most fatal one is that the provider uses inheritedWidgets to deliver the same listeners. This means that any access to its ChangeNotifier class must be within the parent widget tree. The problem of state management for non-parent components, which requires other means (EventBus, global, singleton), is quite painful, but with GetX it becomes more comfortable.


routing

General routing navigation

Open to a new page:

Get.to(NextScreen());
Copy the code

Corresponding native route:

    Navigator.push(context, MaterialPageRoute<void>(
      builder: (BuildContext context) {
        returnNextScreen(); }));Copy the code

Returns:

Get.back();
Copy the code

Corresponding native route:

    Navigator.pop(context);
Copy the code

Open a new page and replace the old page with the new page (delete the old page) :

Get.off(NextScreen());
Copy the code

Corresponding native route:

 Navigator.pushReplacement(context, MaterialPageRoute<void>(
      builder: (BuildContext context) {
        returnNextScreen(); }));Copy the code

Open a new page and delete all previous routes:

Get.offAll(NextScreen());
Copy the code

Corresponding native route:

   Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
          return NextScreen();
        },
      ),
      (Route<dynamic> route) => false,);Copy the code

Navigate to a new page and receive returned data on return:

var data = await Get.to(NextScreen());
Copy the code

Corresponding native route:

    var data = await  Navigator.push(context, MaterialPageRoute<void>(
      builder: (BuildContext context) {
        returnNextScreen(); }));Copy the code

Returns the previous route with a return value, as used above:

Get.back(result: 'success');
Copy the code

Corresponding native route:

 Navigator.pop(context, 'success');

Copy the code

Alias routing navigation

  1. Declare aliases:
abstract class Routes {
  static const Initial = '/';
  static const NextScreen = '/NextScreen';

}
Copy the code
  1. Register routing table:

abstract class AppPages {
  static final pages = [
    GetPage(
      name: Routes.Initial,
      page: () => HomePage(),
    ),
    GetPage(
      name: Routes.NextScreen,
      page: () => NextScreen(),
    ),
  ];
}

Copy the code
  1. Replace the MaterialApp with GetMaterialApp:
void main() {
  runApp(GetMaterialApp(
    debugShowCheckedModeBanner: false,
    initialRoute: '/',
    theme: appThemeData,
    defaultTransition: Transition.fade,
    getPages: AppPages.pages,
    home: HomePage(),
  ));
}
Copy the code

use

Navigate to the next page:

Get.toNamed(Routes.NextScreen);
Copy the code

Navigate to the next page and delete the previous page:

Get.offNamed(Routes.NextScreen);
Copy the code

Navigate to the next page and delete all previous pages:

Get.offAllNamed(Routes.NextScreen);
Copy the code

Send data to alias routes:

Get accepts anything here, whether it’s a string, a Map, a List, or even an instance of a class.

Get. ToNamed (Routes.NextScreen, arguments: 'Niigaki Knot garment ');Copy the code

Get parameters:

String name=Get.arguments;
Copy the code

Dynamic Web links:

Carry parameters like the Web, a style suited to front-end development.

Get.offAllNamed("/NextScreen? device=phone&id=354&name=Enzo");Copy the code

Get parameters:

int id = Get.parameters['id'];
// out: 354
String name=Get.parameters['name'];
Copy the code

Route aliases can also be defined as follows:

       GetPage(
        name: '/profile/:user',
        page: () => UserProfile(),
      ),
Copy the code

Navigation:

Get.toNamed("/profile/34954");

Copy the code

On the second page, you get the data by parameters

print(Get.parameters['user']);
// out: 34954
Copy the code

The middleware

To do something before a jump, such as deciding whether to log in, you can use the routingCallback:

GetMaterialApp(routingCallback: (Routing){if(routing.current == '/second'){// If... }})Copy the code

Widget navigation

SnackBars

Pop up:

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

Corresponding native writing method:

final snackBar = SnackBar( content: Text('Hi! '), action: SnackBarAction( label: 'I am a old and ugly snackbar', onPressed: (){} ), ); // To create a simple SnackBar with Flutter, you must either get the Scaffold context or attach a GlobalKey to your Scaffold. Scaffold.of(context).showSnackBar(snackBar);Copy the code

Dialogs

Open a default Dialog:

Get.defaultDialog(
  onConfirm: () => print("Ok"),
  middleText: "Dialog made in 3 lines of code"
);
Copy the code

Open a custom Dialog:

Get.dialog(YourDialogWidget());
Copy the code

BottomSheets

Get-. bottomSheet is similar to showModalBottomSheet, but without context:

Get.bottomSheet( Container( child: Wrap( children: <Widget>[ ListTile( leading: Icon(Icons.music_note), title: Text('Music'), onTap: () => {} ), ListTile( leading: Icon(Icons.videocam), title: Text('Video'), onTap: () => {},),],),);Copy the code