GetX 入门教程(Android 开发者速通版)
目标:从 0 到 1 使用 GetX 管理路由、状态、依赖注入与常用交互。示例基于 Flutter + GetX 4.x。
1. 依赖引入
在 pubspec.yaml 中添加(你项目已包含 get: ^4.6.6 则跳过):
yaml
dependencies:
get: ^4.6.6
bash
flutter pub get
2. 启动入口:使用 GetMaterialApp
将 MaterialApp 替换为 GetMaterialApp(提供路由/导航/多语言等能力):
dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'GetX Demo',
initialRoute: Routes.home,
getPages: AppPages.pages,
theme: ThemeData.light(),
);
}
}
3. 路由与页面
定义路由常量与页面表:
dart
class Routes {
static const home = '/';
static const detail = '/detail';
}
class AppPages {
static final pages = <GetPage>[
GetPage(name: Routes.home, page: () => const HomePage(), binding: HomeBinding()),
GetPage(name: Routes.detail, page: () => const DetailPage(), binding: DetailBinding()),
];
}
导航方式:
- Get.to(() => DetailPage());
- Get.toNamed(Routes.detail, arguments: {'id': 1});
- Get.offAllNamed(Routes.home);
- Get.back(result: 'ok');
接收参数:
dart
final args = Get.arguments; // 或 Get.parameters['id']
4. 控制器与状态管理
两种常用方案:
- 响应式(Obx + Rx)
dart
class HomeController extends GetxController {
final RxInt counter = 0.obs;
void inc() => counter.value++;
}
class HomePage extends GetView<HomeController> {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(child: Obx(() => Text('count: ${controller.counter.value}'))),
floatingActionButton: FloatingActionButton(onPressed: controller.inc),
);
}
}
- 传统(GetBuilder + update)
dart
class DetailController extends GetxController {
int value = 0;
void inc() { value++; update(); }
}
GetBuilder<DetailController>(builder: (c) => Text('${c.value}'));
对比:
- Obx:细粒度、自动刷新、基于
.obs; - GetBuilder:手动
update(),更接近 setState。
5. 依赖注入(DI)与 Bindings
- 即时注入:
Get.put(HomeController()); - 懒注入:
Get.lazyPut(() => HomeController()); - 查找:
final c = Get.find<HomeController>();
使用 Binding 绑定到路由:
dart
class HomeBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<HomeController>(() => HomeController());
}
}
页面通过:class HomePage extends GetView<HomeController> { ... }
全局服务(常驻):
dart
class AuthService extends GetxService {
Future<AuthService> init() async { /* load token */ return this; }
}
// 启动时:await Get.putAsync(() => AuthService().init());
6. 常用交互(无需 context)
dart
Get.snackbar('标题', '内容', snackPosition: SnackPosition.BOTTOM);
Get.defaultDialog(title: '提示', middleText: '确认吗?', onConfirm: Get.back);
Get.bottomSheet(Container(height: 200, color: Colors.white));
7. 生命周期与 Workers
dart
class HomeController extends GetxController {
final RxString keyword = ''.obs;
@override
void onInit() {
super.onInit();
// 防抖
debounce(keyword, (_) => search(keyword.value), time: const Duration(milliseconds: 300));
}
Future<void> search(String k) async {}
}
其他:onReady() 页面渲染后回调;onClose() 释放资源。
8. 异步与网络调用(示例)
dart
class ApiClient {
Future<String> fetchTitle() async {
await Future.delayed(const Duration(milliseconds: 200));
return 'Hello GetX';
}
}
class DetailController extends GetxController {
final ApiClient api;
DetailController(this.api);
final RxString title = ''.obs;
@override
void onInit() {
super.onInit();
load();
}
Future<void> load() async {
title.value = await api.fetchTitle();
}
}
class DetailBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<ApiClient>(() => ApiClient());
Get.put(DetailController(Get.find<ApiClient>()));
}
}
9. 目录建议(小型项目)
arduino
lib/
modules/
home/
home_view.dart
home_controller.dart
home_binding.dart
detail/
detail_view.dart
detail_controller.dart
detail_binding.dart
routes/
app_pages.dart
app_routes.dart
services/
auth_service.dart
10. 易踩坑
- 忘记用
GetMaterialApp→ 导航/多语言等 API 不可用。 - 混用
Obx与GetBuilder时刷新逻辑混乱 → 明确一处为主。 - 大对象频繁 set → 细化为多个
.obs避免全量重建。 - 依赖注入找不到 → 检查 Binding 是否挂到路由、时序是否在
Get.find之前。
11. 快速清单
- 引入依赖 → 使用
GetMaterialApp - 定义
Routes和GetPage Binding中注册 Controller/Service- 页面通过
GetView<C>获取controller - 状态:Obx(.obs) 或 GetBuilder(update)
- 导航:
Get.to/...,提示:Get.snackbar/dialog/bottomSheet