GetX 入门教程(Android 开发者速通版)

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. 控制器与状态管理

两种常用方案:

  1. 响应式(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),
    );
  }
}
  1. 传统(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 不可用。
  • 混用 ObxGetBuilder 时刷新逻辑混乱 → 明确一处为主。
  • 大对象频繁 set → 细化为多个 .obs 避免全量重建。
  • 依赖注入找不到 → 检查 Binding 是否挂到路由、时序是否在 Get.find 之前。

11. 快速清单

  • 引入依赖 → 使用 GetMaterialApp
  • 定义 RoutesGetPage
  • Binding 中注册 Controller/Service
  • 页面通过 GetView<C> 获取 controller
  • 状态:Obx(.obs) 或 GetBuilder(update)
  • 导航:Get.to/...,提示:Get.snackbar/dialog/bottomSheet

相关推荐
LawrenceLan8 小时前
Flutter 零基础入门(十一):空安全(Null Safety)基础
开发语言·flutter·dart
行者969 小时前
Flutter与OpenHarmony跨平台分享组件深度实践
flutter·harmonyos·鸿蒙
行者969 小时前
Flutter跨平台开发在OpenHarmony上的评分组件实现与优化
开发语言·flutter·harmonyos·鸿蒙
cn_mengbei11 小时前
Flutter for OpenHarmony 实战:IconButton 图标按钮详解
flutter
cn_mengbei12 小时前
Flutter for OpenHarmony 实战:OutlinedButton 边框按钮详解
flutter
2501_9159184112 小时前
只有 Flutter IPA 文件,通过多工具组合完成有效混淆与保护
android·flutter·ios·小程序·uni-app·iphone·webview
JasonBoolean12 小时前
EasyDebug v0.0.4 重磅更新:原生 Http 支持 + 全新日志控制台
flutter
cn_mengbei13 小时前
Flutter for OpenHarmony 实战:TextButton 文本按钮详解
flutter