preface
GetX is not so much a state management library as a treasure chest for simplifying Flutter development. It provides a lot of tools to simplify our development. In this article, we’ll give you an overview of GetX, and then the next chapter will look at how it can be used.
GetX tool introduction
The official documentation provides the following description of GetX:
GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, Intelligent dependency injection, and route management quickly and practically. GetX is a super lightweight and powerful solution for Flutter applications. It combines high-performance state management, intelligent dependency injection, and fast available route management.
GetX actually has more gadgets, as shown in the following example:
routing
Routes Support named and anonymous routes:
Get.to(() => Home());
Get.toNamed('/home');
// Return to the previous page
Get.back();
// Replace with the next page
Get.off(NextScreen());
// Clear the navigation stack of all pages
Get.offAll(NextScreen());
// Get the named route parameters
print(Get.parameters['id']);
print(Get.parameters['name']);
Copy the code
The advantage of GetX routing is that it does not depend on the context and is very concise. For more information about routing, see the official documentation of GetX routing.
SnackBar
There are many limitations to the SnackBar that a Flutter can carry by itself. See: The way that a Flutter properly displays the SnackBar (version 2.0 component changes a little, but is basically the same). GetX is much simpler, and of course has more style configuration and position configuration parameters.
Get.snackbar('SnackBar'.'This is GetX's SnackBar');
Copy the code
dialog
The same goes for dialog boxes. The default dialog box is out of the box.
Get.defaultDialog(
title: 'Dialog box',
content: Text('Dialog contents'),
onConfirm: () {
print('Confirm');
Get.back();
},
onCancel: () {
print('Cancel'); });Copy the code
Memory cache
GetX can cache content objects to share data across different pages. Note that the put operation must be performed before the find operation. Otherwise, exceptions will be thrown.
Get.put(CacheData(name: 'This is cached data'));
CacheData cache = Get.find();
Copy the code
Offline storage
GetX provides a get_storage plug-in for offline storage. Compared to shared_Preferences, get_storage has the advantage of being pure Dart written and not dependent on native, so it can be used on multiple platforms such as Android, iOS, Web, Linux, Mac, etc. GetStorage is based on memory and file storage. When there is data in the memory container, it preferentially reads data from the memory. Specify the file name to store and the container to store the data when building the GetStorage object.
GetStorage storage = GetStorage();
storage.write('name'.'Island code farmer');
storage.read('name');
Copy the code
Change the topic
This can be done in a single line of code with dark and light colors, or you can change it to a custom theme — the boss has already covered most of your need to change the main color to suit your phone case!
Get.changeTheme(
Get.isDarkMode ? ThemeData.light() : ThemeData.dark());
},
Copy the code
Multilingual support
Multi-language support is achieved using a data dictionary, which, when specified by GetMaterialApp (which is an inheritance from Translations), assumes the.tr suffix when using strings, which automatically switches the translation of the string’s language when switching languages.
class GetXDemo extends StatelessWidget {
// omit other code
TextButton(
onPressed: () {
var locale = Locale('en'.'US');
Get.updateLocale(locale);
},
child: Text('name'.tr),
),
}
class Messages extends Translations {
@override
Map<String.Map<String.String>> get keys => {
'en_US': {
'name': 'Island Coder',},'zh_CN': {
'name': 'Island code farmer',}}; }Copy the code
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
translations: Messages(),
locale: Locale('zh'.'CN'),
color: Colors.white,
navigatorKey: Get.key,
title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, brightness: Brightness.light, ), home: GetXDemo(), ); }}Copy the code
The concept of GetX
GetX has three basic concepts: performance, productivity, and Organization.
- Performance: GetX focuses on Performance and minimizes resource consumption. GetX don’t use
Stream
或ChangeNotifier
. - Productivity: GetX uses a concise and pleasant syntax. No matter what you’re doing, GetX will be easy to use. This saves development time and maximizes application performance. In general, developers need to focus on removing controllers from memory. With GetX, you don’t have to do this. Resources are automatically released from memory when the controller is not in use. If resident memory is really needed, it needs to be declared in dependencies
permanent:true
. In this way, you reduce the risk of having too many unnecessary dependent objects in memory. Also, relying on defaults is lazy loading. - Organization: GetX can completely decouple views, presentation logic, business logic, dependency injection, and navigation. No need to jump between routes
context
So our navigation does not depend on the component tree. Nor does it need to be used throughInheritedWidget
的context
Access the controller or BLOC object, so that presentation logic and business logic can be separated from the virtual component layer. We also don’t need to inject Controller/Model/Bloc objects into the component tree like we do with MultiProvider. Therefore, dependency injection and views can be separated.
GetX ecological
GetX has many features that make coding easy. Each feature is independent of each other and only starts when it is used. For example, if only state management is used, then only state management will be compiled. If only routing is used, the state management part is not compiled.
GetX has a large ecosystem that includes a large community of collaborators (132 on GitHub) and promises to maintain Flutter as long as it exists. GetX is compatible with Android, iOS, Web, Mac, Linux and Windows. GetX even has a server-side version of Get_Server. .
To simplify development, GetX also provides the scaffolding tool GET_CLI and the VSCode plug-in GetX Snippets (Android Studio and Intellij plug-ins are also available). The following quick code template is provided:
- Getmain: the main.dart code of GetX;
- Getmodel: Model class code, including fromJson and toJson methods
- Otherwise, type getXXXX to generate as prompted. For details, see GetX Snippets introduction.
conclusion
GetX basically covers a large part of Flutter application development, including routing, themes, multilingual, elastic layers, state management, dependency injection, network request encapsulation, and more. GetX looks like a framework, but its modules are actually independent, and it’s really a toolbox. For development, we can use its whole family bucket, or we can take any required modules from it and use them in our application.
I am island code farmers, wechat public account with the same name. This is a column about getting started with Flutter and its source code.
👍🏻 : feel the harvest please point a praise to encourage!
🌟 : Collect articles, easy to look back!
💬 : Comment exchange, mutual progress!