• Flutter中GetX系列七--依赖注入(put,lazyPut,putAsync)、Binding(统一初始化)


    1.依赖注入

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

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

    我们来看一下代码演示

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

    1. import 'package:flutter/material.dart';
    2. import 'package:flutter_getx_example/DependecyInjectionExample/DependecyInjectionExample.dart';
    3. import 'package:get/get.dart';
    4. void main() {
    5. runApp(MyApp());
    6. }
    7. class MyApp extends StatelessWidget {
    8. @override
    9. Widget build(BuildContext context) {
    10. return GetMaterialApp(
    11. title: "GetX",
    12. home: DependecyInjectionExample(),
    13. );
    14. }
    15. }

    第二步:创建控制器

    1. import 'package:flutter_getx_example/ObxCustomClassExample/Teacher.dart';
    2. import 'package:get/get.dart';
    3. class MyController extends GetxController {
    4. var teacher = Teacher();
    5. void convertToUpperCase() {
    6. teacher.name.value = teacher.name.value.toUpperCase();
    7. }
    8. }

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

    1. import 'package:flutter/material.dart';
    2. import 'package:flutter_getx_example/GetXControllerExample/MyController.dart';
    3. import 'package:get/get.dart';
    4. class DependecyInjectionExample extends StatelessWidget {
    5. @override
    6. Widget build(BuildContext context) {
    7. // 即使不使用控制器实例也会被创建
    8. // tag将用于查找具有标签名称的实例,可以用于创建多个实例的时候进行区分
    9. // 控制器在不使用时被处理,permanent如果永久为真,则实例将在整个应用程序中保持活动状态,不会被释放
    10. MyController myController = Get.put(MyController(), permanent: true);
    11. // MyController myController = Get.put(MyController(), tag: "instancel", permanent: true);
    12. // 实例将在使用时创建(懒加载)
    13. // 它类似于'permanent',区别在于实例在不被使用时被丢弃
    14. // 但是当它再次需要使用时,get 将重新创建实例
    15. // Get.lazyPut(()=> MyController());
    16. // Get.lazyPut(()=> MyController(), tag: "instancel");
    17. // Get.put 异步版本
    18. // Get.putAsync(() async => await MyController());
    19. // 每次都将返回一个新的实例
    20. // Get.create(() => MyController());
    21. return Scaffold(
    22. appBar: AppBar(
    23. title: Text("GetXController"),
    24. ),
    25. body: Center(
    26. child: Column(
    27. mainAxisAlignment: MainAxisAlignment.center,
    28. crossAxisAlignment: CrossAxisAlignment.center,
    29. children: [
    30. ElevatedButton(
    31. onPressed: () {
    32. // 实例使用的tag创建
    33. // Get.find(tag: 'instancel');
    34. Get.find();
    35. },
    36. child: Text("别点我"))
    37. ],
    38. ),
    39. ),
    40. );
    41. }
    42. }

    2.GetX Binding

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

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

    1. import 'package:flutter_getx_example/GetXBindingExample/controller/BindingHomeController.dart';
    2. import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
    3. import 'package:get/get.dart';
    4. //在同一个控制器中将所有的控制器全部进行初始化.因为使用的是lazyPut懒加载,所以再没有使用到的时候并不会进行初始化的.
    5. class AllControllerBinding implements Bindings {
    6. @override
    7. void dependencies() {
    8. // TODO: implement dependencies
    9. Get.lazyPut(() => BindingMyController());
    10. Get.lazyPut(() => BindingHomeController());
    11. }
    12. }
    13. import 'package:get/get.dart';
    14. //第一个控制器
    15. class BindingHomeController extends GetxController {
    16. var count = 0.obs;
    17. void increment() {
    18. count++;
    19. }
    20. }
    21. import 'package:get/get.dart';
    22. //第二个控制器
    23. class BindingMyController extends GetxController {
    24. var count = 0.obs;
    25. void increment() {
    26. count++;
    27. }
    28. }

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

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

    1. import 'package:flutter/material.dart';
    2. import 'package:flutter_getx_example/GetXBindingExample/binding/AllControllerBinding.dart';
    3. import 'package:flutter_getx_example/GetXBindingExample/GetXBindingExample.dart';
    4. import 'package:get/get.dart';
    5. void main() {
    6. runApp(MyApp());
    7. }
    8. class MyApp extends StatelessWidget {
    9. @override
    10. Widget build(BuildContext context) {
    11. /// GetX Binding
    12. return GetMaterialApp(
    13. title: "GetX",
    14. initialBinding: AllControllerBinding(),//必须进行引入(全局绑定的getx Controller)
    15. home: GetXBindingExample(),
    16. );
    17. }
    18. }

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

    1. import 'package:flutter/material.dart';
    2. import 'package:flutter_getx_example/GetXBindingExample/BHome.dart';
    3. import 'package:flutter_getx_example/GetXBindingExample/binding/BHomeControllerBinding.dart';
    4. import 'package:flutter_getx_example/GetXBindingExample/controller/BindingMyController.dart';
    5. import 'package:get/get.dart';
    6. class GetXBindingExample extends StatelessWidget {
    7. @override
    8. Widget build(BuildContext context) {
    9. return Scaffold(
    10. appBar: AppBar(
    11. title: Text("GetXBinding"),
    12. ),
    13. body: Center(
    14. child: Column(
    15. mainAxisAlignment: MainAxisAlignment.center,
    16. crossAxisAlignment: CrossAxisAlignment.center,
    17. children: [
    18. Obx(() => Text(
    19. "计数器的值为 ${Get.find().count}",
    20. style: TextStyle(color: Colors.red, fontSize: 30),
    21. )),
    22. SizedBox(height: 20,),
    23. ElevatedButton(
    24. onPressed: () {
    25. //直接通过Get.find()就可以获取到了,不需要先调用Get.put()方法了.
    26. Get.find().increment();
    27. },
    28. child: Text("点击加1")
    29. ),
    30. SizedBox(height: 20,),
    31. ElevatedButton(
    32. onPressed: () {
    33. Get.to(BHome());
    34. // Get.toNamed("/bHome");
    35. // Get.to(BHome(), binding: BHomeControllerBinding());
    36. },
    37. child: Text("跳转去首页")
    38. ),
    39. ],
    40. ),
    41. ),
    42. );
    43. }
    44. }

    注意事项:
            不如不使用全局的GetX Binding,而是使用了
    <>文章中的单个GetxController,存在的隐患就是如果用户首先点击了get.find()页面,而没有先单击get.put()页面的话,这个时候页面还没有进行初始化,所以就会报错.但是全局就不会存在该问题.

  • 相关阅读:
    easyExcel自定义背景颜色、easyExcel自定义表头背景色
    vmware安装linux操作系统
    .NET应用如何防止被反编译
    使用 Redis 实现分布式锁,解决分布式锁原子性、死锁、误删、可重入、自动续期等问题(使用SpringBoot环境实现)
    B. Permutation Chain
    自回归(AR)模型的功率谱估计
    C语言 - 数组
    【聊天系统的优化】RPC方式的优化
    概率论基础——拉格朗日乘数法
    软件杯 深度学习 python opencv 动物识别与检测
  • 原文地址:https://blog.csdn.net/eastWind1101/article/details/128026390