Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,49 @@ enum Status {
Future<List<Task>> getTasksByStatus(@Path() Status status);
```

#### Using dart_mappable

You can use [dart_mappable](https://pub.dev/packages/dart_mappable) for type conversion by setting the parser to `Parser.DartMappable`:

```dart
@RestApi(
baseUrl: 'https://api.example.com',
parser: Parser.DartMappable,
)
abstract class ApiService {
factory ApiService(Dio dio) = _ApiService;

@GET('/tasks')
Future<List<Task>> getTasks();
}

@MappableClass()
class Task with TaskMappable {
const Task({this.id, this.name});

final String? id;
final String? name;
}
```

Don't forget to add the required dependencies:

```yaml
dependencies:
dart_mappable: ^4.2.0

dev_dependencies:
dart_mappable_builder: ^4.2.0
```

And generate the code:

```sh
dart run build_runner build
```

For a complete example, see the [example_dartmappable](https://github.com/trevorwang/retrofit.dart/tree/master/example_dartmappable) directory.

#### Typed extras
If you want to add static extra to all requests.

Expand Down
15 changes: 15 additions & 0 deletions example_dartmappable/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Files and directories created by pub.
.dart_tool/
.packages
build/
pubspec.lock

# Directory created by dartdoc
doc/api/

# IDEs
.idea/
.vscode/
*.iml
*.ipr
*.iws
73 changes: 73 additions & 0 deletions example_dartmappable/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Dart Mappable Example

This example demonstrates how to use `dart_mappable` with Retrofit for type conversion.

## Setup

1. Add the required dependencies to your `pubspec.yaml`:

```yaml
dependencies:
retrofit: ^4.9.0
dio: ^5.7.0
dart_mappable: ^4.2.0

dev_dependencies:
retrofit_generator: ^10.0.1
build_runner: ^2.4.0
dart_mappable_builder: ^4.2.0
```

2. Define your models with `@MappableClass()`:

```dart
import 'package:dart_mappable/dart_mappable.dart';

part 'example.mapper.dart';

@MappableClass()
class Task with TaskMappable {
const Task({
this.id,
this.name,
this.avatar,
this.createdAt,
});

final String? id;
final String? name;
final String? avatar;
final String? createdAt;
}
```

3. Create your API client with `Parser.DartMappable`:

```dart
import 'package:retrofit/retrofit.dart';

part 'example.g.dart';

@RestApi(
baseUrl: 'https://api.example.com',
parser: Parser.DartMappable,
)
abstract class ApiService {
factory ApiService(Dio dio) = _ApiService;

@GET('/tasks')
Future<List<Task>> getTasks();
}
```

4. Generate code:

```bash
dart run build_runner build
```

## Running the Example

```bash
dart run bin/main.dart
```
10 changes: 10 additions & 0 deletions example_dartmappable/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
include: package:lints/recommended.yaml

analyzer:
exclude:
- "**/*.g.dart"
- "**/*.mapper.dart"

linter:
rules:
- avoid_print
44 changes: 44 additions & 0 deletions example_dartmappable/bin/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:retrofit_example_dartmappable/example.dart';

final logger = Logger();

Future<void> main(List<String> args) async {
final dio = Dio();
dio.options.headers['Demo-Header'] = 'demo header';
dio.options.headers['Content-Type'] = 'application/json';
final client = ApiService(dio);

// Get all tasks
client.getTasks().then((it) => logger.i(it));

// Get a single task
client.getTask('2').then((it) => logger.i(it)).catchError((Object obj) {
switch (obj.runtimeType) {
case DioException _:
final res = (obj as DioException).response;
logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
default:
}
});

// Create a new task
client.createTask(const Task(avatar: '2222.png', name: 'new task')).then((it) {
logger.i(it.toMap());
});

// Update a task
client
.updateTask('3', const Task(id: '4', avatar: '1.png', name: 'number 3'))
.then((it) {
logger.i(it.toMap());
});

// Delete a task
client.deleteTask('2').then((it) {
logger.i('Task 2 has been deleted!');
}).catchError((Object err) {
logger.e(err);
});
}
48 changes: 48 additions & 0 deletions example_dartmappable/lib/example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import 'package:dart_mappable/dart_mappable.dart';
import 'package:dio/dio.dart' hide Headers;
import 'package:retrofit/retrofit.dart';

part 'example.mapper.dart';
part 'example.g.dart';

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

@GET('/tasks')
Future<List<Task>> getTasks();

@GET('/tasks/{id}')
Future<Task> getTask(@Path('id') String id);

@POST('/tasks')
Future<Task> createTask(@Body() Task task);

@PUT('/tasks/{id}')
Future<Task> updateTask(@Path() String id, @Body() Task task);

@DELETE('/tasks/{id}')
Future<void> deleteTask(@Path() String id);
}

@MappableClass()
class Task with TaskMappable {
const Task({
this.id,
this.name,
this.avatar,
this.createdAt,
});

final String? id;
final String? name;
final String? avatar;
final String? createdAt;
}
Loading
Loading