gpt4 book ai didi

Dart:类型 'Null' 不是 Mockito 中类型 'Future' 的子类型

转载 作者:行者123 更新时间:2023-12-04 05:53:33 26 4
gpt4 key购买 nike

下面的代码曾经在空安全之前工作,但现在我得到“类型 'Null' 不是类型 'Future ' 的子类型”,我完全不知道为什么以及该怎么做。请帮忙,这应该很容易(除了我),因为您只需要复制代码并将其作为测试运行即可获得异常:

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

void main() {

group('all', () {

test('test', () async {
final mockMethodChannel = MockMethodChannel();
when(mockMethodChannel
.invokeMethod<String>("GET com.eight/preference-management/preferences"))
.thenAnswer((_) async => "test");
});
});
}

最佳答案

您的签名 MethodChannel.invokeMethod函数说它返回一个 Future<String?>但自从MockMethodChannel invokeMethod() 没有任何实现,它将返回 null ; dart 的 null 安全会因为你撒谎而生气。如需快速修复,请使用 invokeMethod可以有 Future<String?>? 的返回类型.当您这样做时,您是在说即使返回值为 null 也不应该打扰 null 安全。
然而,这不是一个永久的解决方案,我只是想让你理解这个问题。
您可以在 dev_dependencies: in pubspec.yaml 中添加 build_runnerdart pub add build_runner --dev并将您的代码修改为

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
//modified
import 'package:mockito/annotations.dart';
import 'generated file.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

//modified
@GenerateMocks([MockMethodChannel])
void main() {

group('all', () {

test('test', () async {
final mockMethodChannel = MockMockMethodChannel();
when(mockMethodChannel
.invokeMethod<String>("GET com.eight/preference-management/preferences"))
.thenAnswer((_) async => "test");
});
});
}
并运行 flutter pub run build_runner build --delete-conflicting-outputs用于构建运行器为您构建 stub 文件

关于Dart:类型 'Null' 不是 Mockito 中类型 'Future<String?>' 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67371802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com