依赖注入(put,lazyPut,putAsync)、Binding(统一初始化)

41 阅读3分钟

1.依赖注入

在前面的文章中,我们经常使用Get.put(MyController())来进行控制器实例的创建,这样我们就算不使用控制器实例也会被创建,其实GetX还提供很多创建实例的方法,可根据不同的业务来进行创建,接下来我们简单介绍一下几个最常用的

  • **Get.put():**不使用控制器实例也会被创建
  • **Get.lazyPut():**懒加载方式创建实例,只有在使用时才创建
  • Get.putAsync(): `Get.put()`的异步版版本
  • Get.create(): 每次使用都会创建一个新的实例

我们来看一下代码演示

第一步:应用程序入口配置

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/DependecyInjectionExample/DependecyInjectionExample.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX",
      home: DependecyInjectionExample(),
    );
  }
}

第二步:创建控制器

import 'package:flutter_getx_example/ObxCustomClassExample/Teacher.dart';
import 'package:get/get.dart';

class MyController extends GetxController {
  var teacher = Teacher();
  
  void convertToUpperCase() {
     teacher.name.value = teacher.name.value.toUpperCase();
  }
}

第三步:实例化控制器并使用

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerExample/MyController.dart';
import 'package:get/get.dart';

class DependecyInjectionExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    // 即使不使用控制器实例也会被创建
    // tag将用于查找具有标签名称的实例,可以用于创建多个实例的时候进行区分
    // 控制器在不使用时被处理,permanent如果永久为真,则实例将在整个应用程序中保持活动状态,不会被释放
    MyController myController = Get.put(MyController(), permanent: true);
    // MyController myController = Get.put(MyController(), tag: "instancel", permanent: true);


    // 实例将在使用时创建(懒加载)
    // 它类似于'permanent',区别在于实例在不被使用时被丢弃
    // 但是当它再次需要使用时,get 将重新创建实例
    // Get.lazyPut(()=> MyController());
    // Get.lazyPut(()=> MyController(), tag: "instancel");



    // Get.put 异步版本
    // Get.putAsync<MyController>(() async  => await MyController());



    // 每次都将返回一个新的实例
    // Get.create<MyController>(() => MyController());

    return Scaffold(
      appBar: AppBar(
        title: Text("GetXController"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                // 实例使用的tag创建
                // Get.find<MyController>(tag: 'instancel');

                Get.find<MyController>();
              },
              child: Text("别点我"))
          ],
        ),
      ),
    );
  }
}

2.GetX Binding

在我们使用GetX状态管理器的时候,往往每次都是用需要手动实例化一个控制器,这样的话基本页面都需要实例化一次,这样就太麻烦了,而Binding 能解决上述问题,可以在项目初始化时把所有需要进行状态管理的控制器进行统一初始化,接下来看代码演示:

第一步:声明需要进行的绑定控制器类

import 'package:flutter_getx_example/GetXBindingExample/controller/BindingHomeController.dart';
import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
import 'package:get/get.dart';

//在同一个控制器中将所有的控制器全部进行初始化.因为使用的是lazyPut懒加载,所以再没有使用到的时候并不会进行初始化的.
class AllControllerBinding implements Bindings {
  
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<BindingMyController>(() => BindingMyController());
    Get.lazyPut<BindingHomeController>(() => BindingHomeController());
  }
}



import 'package:get/get.dart';

//第一个控制器
class BindingHomeController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}


import 'package:get/get.dart';

//第二个控制器
class BindingMyController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}

第二步:在项目启动时进行初始化绑定

绑定的方式有多种,在不同的情况下有不同的使用方式,这里介绍一种.

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXBindingExample/binding/AllControllerBinding.dart';
import 'package:flutter_getx_example/GetXBindingExample/GetXBindingExample.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /// GetX Binding
    return GetMaterialApp(
      title: "GetX",
      initialBinding: AllControllerBinding(),
      home: GetXBindingExample(),
    );
  }
}

第三步:在页面中使用状态管理器

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXBindingExample/BHome.dart';
import 'package:flutter_getx_example/GetXBindingExample/binding/BHomeControllerBinding.dart';
import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
import 'package:get/get.dart';

class GetXBindingExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GetXBinding"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Obx(() => Text(
              "计数器的值为 ${Get.find<BindingMyController>().count}",
              style: TextStyle(color: Colors.red, fontSize: 30),
            )),
            SizedBox(height: 20,),
            ElevatedButton(
              onPressed: () {
                Get.find<BindingMyController>().increment();
              },
              child: Text("点击加1")
            ),
            SizedBox(height: 20,),
            ElevatedButton(
              onPressed: () {
                Get.to(BHome());

                // Get.toNamed("/bHome");

                // Get.to(BHome(), binding: BHomeControllerBinding());
              },
              child: Text("跳转去首页")
            ),
          ],
        ),
      ),
    );
  }
}

本文转自 blog.csdn.net/eastWind110…,如有侵权,请联系删除。