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,
);
}
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:
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 'package:retrofit/retrofit.dart' as rf;
rf.Headers()
@rf.Headers({
'contentType': 'application/json',
})
@POST('path')
Future<User> createUser(
@Body() User user,
);