GetX Bindings 绑定的套路写法

9 min read

Binding 类是一个将依赖注入进行分离,同时“绑定”到 状态管理器Controller 和 路由管理器中,简单说,就是把UI 中的 控制器实例化部分抽离出来了,抽离时需要实现 Bindings 类

创建控制器

class MyController extends GetxController {
  final _nums = ["1", "2", "3"];
  List<String> get nums => _nums;
}

创建bindings

// 
class MyBinding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut<MyController>(() => MyController());
    // ... 其它控制器
  }
}

将binding绑定到路由

GetPage(
   name: '/binding',
   page: () => MyPage(),
   binding: MyBinding(),
),

在视图层使用 bings

class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("依赖管理4"),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Text("演示tag参数"),
          Row(
            children: Get.find<MyController>()
                .works
                .map((item) => Text("$item"))
                .toList(),
          )
        ],
      ),
    );
  }
}

使用GetView代替StatelessWidget

可以直接使用 controller 调用, 只用于只有一个控制器时

class MyPage extends GetView<MyController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("依赖管理4"),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Text("演示拿到数据:${controller.title}"),
        ],
      ),
    );
  }
}