I get Error: Type 'Dio' not found when using Retrofit and Dio together

Viewed 14

I just added retrofit to my Flutter app and generated a class as explained here.

But when I want to run my app I get the following error:

Running Gradle task 'assembleAppdevDebug'...                    
lib/folder/service.g.dart:14:9: Error: Type 'Dio' not found.

I use the following dependencies

dependencies:
  dio: ^4.0.6
  retrofit: 3.0.1

dev_dependencies:
  json_serializable: ^6.2.0
  analyzer: ^2.8.0
  build_verify: ^3.0.0
  retrofit_generator: 3.0.1
  build_runner: ^2.1.2

The class definition looks like this

@RestApi(baseUrl: 'https://someapi.com/')
abstract classService {
  factory Service(dio.Dio dio, {String baseUrl}) = _Service;

  @Headers({
    'contentType': 'application/json',
  })
  @POST('path')
  Future<User> createUser(
    @Body() User user,
  );
}

1 Answers

I found out what the problem was. When I defined the abstract class and added the @Headers annotation the IDE complained that both DIO and Retrofit contained a headers annotation and that I therefore should specify an alias import:

enter image description here

Which I then did by specifying import 'package:dio/dio.dart' as dio;

The alias import though was the reason why the generated _Service file couldn't find Dio.

Solution:

  • Import retrofit as import 'package:retrofit/retrofit.dart' as rf;
  • Define the headers as rf.Headers()
@rf.Headers({
    'contentType': 'application/json',
})
@POST('path')
Future<User> createUser(
  @Body() User user,
);
Related