Flutter GetX Syntax Cheat Sheet
State Management
Creating a GetXController:
Dart
import 'package:get/get.dart';
class MyController extends GetxController {
var count = 0.obs;
void increment() {
count++;
}
}
Using a GetXController in a Widget:
Dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class MyWidget extends StatelessWidget {
final MyController controller = Get.put(MyController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('GetX Example')),
body: Center(
child: Obx(() => Text('Count: ${controller.count}')),
),
floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
child: Icon(Icons.add),
),
);
}
}
Dependency Injection
Injecting a Dependency:
Dart
class MyService {
void doSomething() {
print('Doing something...');
}
}
class MyController extends GetxController {
final MyService service = Get.find();
void callService() {
service.doSomething();
}
}
Route Management
Defining Named Routes:
Dart
Get.lazyRoutes([
GetPage(name: '/home', page: () => HomePage()),
GetPage(name: '/about', page: () => AboutPage()),
]);
Navigating to a Route:
Dart
Get.toNamed('/about');
Passing Arguments:
Dart
Get.toNamed('/about', arguments: {'name': 'John'});
Snackbar and Dialogs
Showing a Snackbar:
Dart
Get.snackbar('Title', 'Message', backgroundColor: Colors.red);
Showing a Dialog:
Dart
Get.defaultDialog(
title: 'Title',
content: Text('Content'),
onConfirm: () {
// Do something when confirmed
},
);
Internationalization (i18n)
Creating Translations:
Dart
// en_US.dart
class EnUsTranslations extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'home': {
'title': 'Home',
'message': 'Welcome',
},
};
}
Using Translations:
Dart
Get.translations = Translations();
Get.updateLocale(Locale('en', 'US'));
// In your widget:
Text(Get.translations.translate('home.title'))
Reactive Programming
Using obs
:
Dart
var count = 0.obs;
Observing Changes:
Dart
Obx(() => Text('Count: ${count.value}'))
Middlewares
Creating a Middleware:
Dart
class MyMiddleware extends GetMiddleware {
@override
Future<GetMiddlewareResult> onInit(Request req, GetMiddlewareResult result) async {
// Do something before the route is executed
return result;
}
}
Using a Middleware:
Dart
Get.addRoutes([
GetPage(name: '/home', page: () => HomePage(), middlewares: [MyMiddleware()]),
]);
Bindings
Creating a Binding:
Dart
class MyBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => MyController());
}
}
Using a Binding:
Dart
Get.lazyRoute(
name: '/home',
page: () => HomePage(),
binding: MyBinding(),
);
Komentar
Posting Komentar