Your signature for MethodChannel.invokeMethod function says it returns a Future<String?> but since the MockMethodChannel doesnot have any implementation for invokeMethod() , it will return null; dart’s null safety gets angry because you lied. For a quick fix, the invokeMethod can have a return type of Future<String?>?. When you do so, you are saying null safety shouldn’t bother even if the returned value is null.
However this is not a permanent solution I just want you to understand the problem.
you could add build_runner in your dev_dependencies: in pubspec.yaml
dart pub add build_runner --dev
and modify your code to
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");
});
});
}
and run
flutter pub run build_runner build --delete-conflicting-outputs for build runner to build the stub files for you