Skip to content

Commit

Permalink
Format code, update examples, remove tuple (#707)
Browse files Browse the repository at this point in the history
* Fix deprecations of `withNullability`

* Small fix

Add back _displayString

* Update versions

* Update retrofit version in retrofit_generator

* Add topics

* Format code, update examples, remove tuple

* Add question mark

* Update flutter_example
  • Loading branch information
Carapacik authored Sep 8, 2024
1 parent f1409e8 commit 89941db
Show file tree
Hide file tree
Showing 81 changed files with 630 additions and 2,311 deletions.
30 changes: 14 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ Add the generator to your dev dependencies

```yaml
dependencies:
retrofit: ^4.3.0
logger: ^1.2.0 # for logging purpose
retrofit: ^4.4.0
logger: ^2.4.0 # for logging purpose
json_annotation: ^4.9.0

dev_dependencies:
Expand All @@ -36,7 +36,7 @@ part 'example.g.dart';

@RestApi(baseUrl: 'https://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1/')
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;

@GET('/tasks')
Future<List<Task>> getTasks();
Expand All @@ -62,9 +62,6 @@ then run the generator
```sh
# dart
dart pub run build_runner build

# flutter
flutter pub run build_runner build
```

### Use it
Expand All @@ -85,8 +82,6 @@ void main(List<String> args) {
}
```



## More

### Type Conversion
Expand Down Expand Up @@ -123,11 +118,14 @@ The HTTP methods in the below sample are supported.
@Query('apikey') String apiKey,
@Query('scope') String scope,
@Query('type') String type,
@Query('from') int from);
@Query('from') int from,
);
@PATCH('/tasks/{id}')
Future<Task> updateTaskPart(
@Path() String id, @Body() Map<String, dynamic> map);
@Path() String id,
@Body() Map<String, dynamic> map,
);
@PUT('/tasks/{id}')
Future<Task> updateTask(@Path() String id, @Body() Task task);
Expand Down Expand Up @@ -191,9 +189,9 @@ client.getTask('2').then((it) {
}).catchError((obj) {
// non-200 error goes here.
switch (obj.runtimeType) {
case DioError:
case DioException:
// Here's the sample to get the failed response error code and message
final res = (obj as DioError).response;
final res = (obj as DioException).response;
logger.e('Got error : ${res.statusCode} -> ${res.statusMessage}');
break;
default:
Expand All @@ -209,7 +207,7 @@ If you want to use a relative `baseUrl` value in the `RestApi` annotation of the
```dart
@RestApi(baseUrl: '/tasks')
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
@GET('{id}')
Future<HttpResponse<Task>> getTask(@Path('id') String id);
Expand All @@ -229,7 +227,7 @@ If you want to use multiple endpoints to your `RestClient`, you should pass your
```dart
@RestApi(baseUrl: 'this url will be ignored if baseUrl is passed')
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
}
final client = RestClient(dio, baseUrl: 'your base url');
Expand Down Expand Up @@ -267,7 +265,7 @@ E.g.
parser: Parser.FlutterCompute,
)
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
@GET('/task')
Future<Task> getTask();
Expand Down Expand Up @@ -298,7 +296,7 @@ Avoid using Map values, otherwise multiple background isolates will be spawned t

```dart
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
// BAD
@GET('/tasks')
Expand Down
2 changes: 1 addition & 1 deletion docs/http/RestApi/baseUrl.html
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ <h5>RestApi class</h5>
</section>
<section class="summary source-code" id="source">
<h2><span>Implementation</span></h2>
<pre class="language-dart"><code class="language-dart">final String baseUrl
<pre class="language-dart"><code class="language-dart">final String? baseUrl

</code></pre>
</section>
Expand Down
2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ <h3 id="define-and-generate-your-api">Define and Generate your API</h3>

@RestApi(baseUrl: "https://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1/")
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;

@GET("/tasks")
Future&lt;List&lt;Task&gt;&gt; getTasks();
Expand Down
3 changes: 1 addition & 2 deletions example/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
include: package:lints/recommended.yaml
analyzer:
exclude:
- lib/**/*.reflectable.dart
- lib/**/*.g.dart
- '**/*.g.dart'
4 changes: 3 additions & 1 deletion example/lib/api_result.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ class ApiResult<T> {
});

factory ApiResult.fromJson(
Map<String, dynamic> json, T Function(Object?) fromJsonT) =>
Map<String, dynamic> json,
T Function(Object?) fromJsonT,
) =>
_$ApiResultFromJson(json, fromJsonT);

///接口调用成功的code码
Expand Down
6 changes: 5 additions & 1 deletion example/lib/auth_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ part 'auth_client.g.dart';

@RestApi()
abstract class AuthClient {
factory AuthClient(Dio dio, {String? baseUrl, ParseErrorLogger errorLogger}) = RestClientYmlp;
factory AuthClient(
Dio dio, {
String? baseUrl,
ParseErrorLogger? errorLogger,
}) = RestClientYmlp;

@POST('/api/auth/mqttClient/authentication')
Future<Object?> authenticationUsingPost({
Expand Down
24 changes: 15 additions & 9 deletions example/lib/example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ part 'example.g.dart';

@RestApi(baseUrl: 'https://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1/')
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl, ParseErrorLogger errorLogger}) = RestClientYmlp;
factory RestClient(
Dio dio, {
String? baseUrl,
ParseErrorLogger? errorLogger,
}) = RestClientYmlp;

@GET('/tasks/{id}')
Future<ApiResult<Task?>> getNestApiResultGenericsInnerTypeNullable();
Expand Down Expand Up @@ -66,7 +70,9 @@ abstract class RestClient {
@PreventNullToAbsent()
@PATCH('/tasks/{id}')
Future<Task> updateTaskAvatar(
@Path() String id, @Field('avatar') String? avatar);
@Path() String id,
@Field('avatar') String? avatar,
);

@DELETE('/tasks/{id}')
Future<void> deleteTask(@Path() String id);
Expand Down Expand Up @@ -105,7 +111,7 @@ abstract class RestClient {
Future<dynamic> headRequest2();

@HEAD('/')
Future<HttpResponse> headRequest3();
Future<HttpResponse<dynamic>> headRequest3();

@GET('/task/group')
Future<List<TaskGroup>> groupedTaskByDate();
Expand All @@ -131,14 +137,14 @@ abstract class RestClient {

@POST('/post')
Future<String> postFormData3({
@Part(value: 'customfiles', contentType: 'application/json')
@Part(name: 'customfiles', contentType: 'application/json')
required List<File> files,
@Part(fileName: 'abc.txt') required File file,
});

@POST('/post')
Future<String> postFormData6({
@Part(value: 'customfiles') required List<List<int>> files,
@Part(name: 'customfiles') required List<List<int>> files,
@Part(fileName: 'abc.txt') required List<int> file,
});

Expand All @@ -161,7 +167,7 @@ abstract class RestClient {
@GET('/enums')
Future<String> queryByEnum(
@Query('tasks') TaskQuery query,
@Query("date") DateTime time,
@Query('date') DateTime time,
);

@GET('/get')
Expand All @@ -175,7 +181,7 @@ abstract class RestClient {
@POST('/postfile')
@Headers(<String, dynamic>{
r'$Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': 'abc'
'Ocp-Apim-Subscription-Key': 'abc',
})
Future<String> postFile({@Body() required File file});

Expand Down Expand Up @@ -253,8 +259,8 @@ abstract class RestClient {
@MultiPart()
@POST('post/{id}/comments/{commentId}')
Future<String> multipartBodyWithMultiplePathParameter(
@Path("id") String id,
@Path("commentId") String commentId,
@Path('id') String id,
@Path('commentId') String commentId,
@Part() Map<String, dynamic> body,
);
}
Expand Down
25 changes: 12 additions & 13 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
name: retrofit_example
description: Retrofit generator
version: 1.0.0

description: retrofit_example
version: 1.0.0+1
environment:
sdk: '>=2.18.0 <3.0.0'
sdk: '>=3.3.0 <4.0.0'

dependencies:
dio: ^5.7.0
http_parser: ^4.0.2
json_annotation: ^4.9.0
logger: ^2.4.0
retrofit:
json_annotation:
logger: ^1.2.2
dio: ^5.0.1

dev_dependencies:
test: ^1.23.1
retrofit_generator:
build_runner: ^2.3.3
json_serializable: ^6.6.1
build_runner: ^2.4.0
json_serializable: ^6.8.0
lints: ^4.0.0
mock_web_server: ^5.0.0-nullsafety.1
lints: ^2.0.1
retrofit_generator:
test: ^1.25.0

dependency_overrides:
retrofit:
path: ../retrofit
retrofit_generator:
path: ../generator
# source_gen: '>=1.3.0 <1.4.0'
15 changes: 9 additions & 6 deletions example/test/example_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import 'task_data.dart';
late MockWebServer _server;
late RestClient _client;
final _headers = {'Content-Type': 'application/json'};
final dispatcherMap = <String, MockResponse>{};

void main() {
setUp(() async {
Expand All @@ -36,8 +35,9 @@ void main() {
test('test tag list', () async {
print(jsonEncode(['tag1', 'tag2']));
_server.enqueue(
body: jsonEncode(['tag1', 'tag2']),
headers: {'Content-Type': 'application/json'});
body: jsonEncode(['tag1', 'tag2']),
headers: {'Content-Type': 'application/json'},
);
final tasks = await _client.getTags();
expect(tasks, isNotNull);
expect(tasks.length, 2);
Expand All @@ -46,8 +46,9 @@ void main() {
test('test stream tag list', () async {
print(jsonEncode(['tag1', 'tag2']));
_server.enqueue(
body: jsonEncode(['tag1', 'tag2']),
headers: {'Content-Type': 'application/json'});
body: jsonEncode(['tag1', 'tag2']),
headers: {'Content-Type': 'application/json'},
);
final tasksStream = _client.getTagsAsStream();
final tasks = await tasksStream.first;
expect(tasks, isNotNull);
Expand All @@ -56,7 +57,9 @@ void main() {

test('test empty task list', () async {
_server.enqueue(
body: demoEmptyListJson, headers: {'Content-Type': 'application/json'});
body: demoEmptyListJson,
headers: {'Content-Type': 'application/json'},
);
final tasks = await _client.getTasks();
expect(tasks, isNotNull);
expect(tasks.length, 0);
Expand Down
2 changes: 1 addition & 1 deletion example/test/task_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'dart:convert';

import 'package:retrofit_example/example.dart';

final demoTask = Task(
const demoTask = Task(
id: '123455151',
name: 'demo task',
avatar:
Expand Down
8 changes: 3 additions & 5 deletions example_dartmapper/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
include: package:lints/recommended.yaml
analyzer:
# strong-mode:
# implicit-casts: false
# implicit-dynamic: false
exclude:
- lib/**/*.reflectable.dart
- lib/**/*.g.dart
- '**/*.g.dart'
- '**/*.reflectable.dart'
Loading

0 comments on commit 89941db

Please sign in to comment.