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

Posted

技术标签:

【中文标题】Flutter/Dart get_It 单例定位器方法失败【英文标题】:Flutter/Dart get_It singleton locator method failure 【发布时间】:2021-12-19 18:52:48 【问题描述】:

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

import 'package:flutter/material.dart';

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

(注意:以上是一个示例,实际的类确实有更多的临时函数。)

我的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.<…>

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

非常感谢任何帮助。

【问题讨论】:

【参考方案1】:

我能够通过执行以下操作来解决此问题:

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

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

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

GetIt dependencyLocator = GetIt.instance;

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

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

【讨论】:

以上是关于Flutter/Dart get_It 单例定位器方法失败的主要内容,如果未能解决你的问题,请参考以下文章

如何将 get_it 用于 Provider.of<ExampleProvider>(context)?

flutter Dart语言List如何获取索引值

颤振无法导入`flutter_webrtc.dart`

Flutter - dart.ui 没有方法'platformViewRegistry'

不会Dart,还搞什么Flutter?

Flutter——实操踩坑:升级Flutter dart