Last updated:
0 purchases
nimbus annotation
Nimbus Generator #
nimbus_generator is a type conversion Nimbus client generator using source_gen and inspired by Chopper and Retrofit.
Usage #
Generator #
Add the generator to your dev dependencies
dependencies:
nimbus4flutter: any
nimbus_annotation: any
dev_dependencies:
nimbus_generator: any
build_runner: any
copied to clipboard
Define and Generate your API #
import 'package:http/http.dart';
import 'package:nimbus4flutter/nimbus4flutter.dart';
import 'package:nimbus_annotation/nimbus_annotation.dart';
part 'example.g.dart';
@NimbusApi()
abstract class ApiService {
factory ApiService({
required String baseUrl,
ApiServerHttpRequestBuilder? requestBuilder,
ApiServerHttpResponseParser? responseParser,
}) = _ApiService;
@GET('/tasks')
Future<List<Task>> getTasks();
}
@DatasetSerializable()
class Task {
const Task({this.common});
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
@DatasetHeader()
final CommonRecord? common;
Map<String, dynamic> toJson() => _$TaskToJson(this);
}
@RecordSerializable()
class CommonRecord {
CommonRecord({this.resultCode, this.resultMessage});
factory CommonRecord.fromJson(Map<String, dynamic> json) =>
_$CommonRecordFromJson(json);
static RecordSchema? get schema => _$CommonRecordSchema();
Map<String, dynamic> toJson() => _$CommonRecordToJson(this);
final String? resultCode;
final String? resultMessage;
}
copied to clipboard
then run the generator
# dart
dart pub run build_runner build
# flutter
flutter pub run build_runner build
copied to clipboard
Use it #
import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:retrofit_example/example.dart';
final logger = Logger();
void main(List<String> args) {
final client = ApiService(
baseUrl: 'localhost:8080',
requestBuilder: (request, method, input) async {
request.headers['Content-Type'] = 'application/json; charset=utf-8';
request.as<http.Request>()?.body = jsonEncode(input);
},
responseParser: (response, method, output) async {
if (response.statusCode != HttpStatus.ok) {
throw Exception('error status = ${response.statusCode}');
}
if (response is http.Response) {
final json = const JsonDecoder().convert(response.body);
(output as Map<String, dynamic>).addAll(json);
}
}
);
client.getTasks().then((it) => logger.i(it));
}
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.