Flutter/Dart get_It 单例定位器方法失败

Flutter/Dart get_It singleton locator method failure

我有一个简单的飞镖class如下:

import 'package:flutter/material.dart';

class UiUtils {
  // TEMPORARY FOR UNIT TEST PURPOSES ONLY
  int addition(int x, int y) {
    return x + y;
  }
}

(注:以上为示例,实际class确实不止那个temp功能。)

我的 pubspec.yml 文件包含以下内容:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.17.0

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  get_it: ^7.1.3
  provider: ^6.0.1
  mockito: ^5.0.16

我有一个 dependency locator 文件:

import 'package:get_it/get_it.dart';
import 'package:quiz_test/utils/UiUtils.dart';

GetIt dependencyLocator = GetIt.instance;

void setupDependencyLocator() {
  //dependencyLocator.registerSingleton(() => UiUtils());
  dependencyLocator.registerFactory(() => UiUtils());
}

最后,在 main.dart 我有以下内容:

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

(当然还有比这更多的代码)

正如所显示的那样,代码工作正常,但是如果我将 dependancy_locator 文件从当前工厂方法更改为单例(即注释掉一个以启用另一个),我会收到以下错误:

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type '_ServiceFactory<() => UiUtils, void, void>' is not a subtype of type '_ServiceFactory<Object, dynamic, dynamic>' of 'value'
#0      _LinkedHashMapMixin.[]= (dart:collection-patch/compact_hash.dart)
#1      _GetItImplementation._register (package:get_it/get_it_impl.dart:844:35)
#2      _GetItImplementation.registerSingleton (package:get_it/get_it_impl.dart:587:5)
#3      setupDependencyLocator (package:quiz_test/utils/dependency_locator.dart:7:21)
#4      main (package:quiz_test/main.dart:13:3)
#5      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#6      _rootRun (dart:async/zone.dart:1428:13)
#7      _CustomZone.run (dart:async/zone.dart:1328:19)
#8      _runZoned (dart:async/zone.dart:1863:10)
#9      runZonedGuarded (dart:async/zone.dart:1851:12)
#10     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:141:5)
#11     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.<…>

谁能帮我理解为什么我不能使用单例调用而不是工厂调用?我的想法是我不需要这个 class 的唯一实例,这是我相信工厂会给我的,我只需要它的单个实例用于任何需要它的 classes。

非常感谢任何帮助。

我通过执行以下操作解决了这个问题:

dependencyLocator.registerSingleton<UiUtils>(UiUtils());

所以,我的 dependencyLocator class 现在看起来像这样:

import 'package:get_it/get_it.dart';
import 'package:quiz_test/utils/UiUtils.dart';

GetIt dependencyLocator = GetIt.instance;

void setupDependencyLocator() {
  dependencyLocator.registerSingleton<UiUtils>(UiUtils());
}

我希望这可以帮助其他人避免陷入困境!