All Projects → trevorwang → Retrofit.dart

trevorwang / Retrofit.dart

Licence: mit
retrofit.dart is an dio client generator using source_gen and inspired by Chopper and Retrofit.

Programming Languages

dart
5743 projects

Projects that are alternatives of or similar to Retrofit.dart

AndroidGo
Android、Flutter 开发者帮助 APP。包含事件分发、性能分析、Google Jetpack组件、OkHttp、RxJava、Retrofit、Volley、Canvas绘制以及优秀博文代码案例等内容,帮助开发者快速上手!
Stars: ✭ 30 (-94.43%)
Mutual labels:  retrofit
Githubfollows
A demo project based on MVVM architecture and material design & animations.
Stars: ✭ 272 (-49.54%)
Mutual labels:  retrofit
Mvvm Juejin
高仿"掘金Android App": databinding + kotlin + rx 的优雅实践。(持续打磨中~)
Stars: ✭ 403 (-25.23%)
Mutual labels:  retrofit
Covid19Tracker
A Robinhood style COVID-19 🦠 Android tracking app for the US. Open source and built with Kotlin.
Stars: ✭ 65 (-87.94%)
Mutual labels:  retrofit
T Mvp
Android AOP Architecture by Apt, AspectJ, Javassisit, based on Realm+Databinding+MVP+Retrofit+Rxjava2
Stars: ✭ 2,740 (+408.35%)
Mutual labels:  retrofit
Clean Android Code
MVP + Dagger 2 + RxJava + Retrofit2
Stars: ✭ 311 (-42.3%)
Mutual labels:  retrofit
tuya-connector
tuya-connector helps you efficiently create cloud development projects regarding the OpenAPI or message subscription capabilities. You can put all the focus on business logic without taking care of server-side programming nor relational databases.
Stars: ✭ 28 (-94.81%)
Mutual labels:  retrofit
Viabus Architecture
让 Android 开发可以像流水线一样高效的,职责分离架构 ⚡ 不同于 MVP 的配置解耦,也不能和 似是而非 的 MVVM - Clean 同日而语。VIABUS 是世界范围内首个明确提出,通过职责分离,来真正实现 UI 和 业务并行开发的 Android 项目级开发架构和设计模式理念。
Stars: ✭ 485 (-10.02%)
Mutual labels:  retrofit
Kotlinwanandroid
Kotlin+模块化+响应式+MVVM 实现的风格简约、代码优雅的WanAndroid客户端
Stars: ✭ 265 (-50.83%)
Mutual labels:  retrofit
Sandwich
🥪 A lightweight and standardized Android network response interface for handling successful data and error responses.
Stars: ✭ 370 (-31.35%)
Mutual labels:  retrofit
Readhub
Readhub AndroidClient
Stars: ✭ 40 (-92.58%)
Mutual labels:  retrofit
android-retrofix
Backports Java 8 APIs (java.util.Optional, java.util.function, java.util.stream, java.util.concurrent.CompletableFuture, java.time) to Android below API 24 (Android 7.0 Nougat)
Stars: ✭ 51 (-90.54%)
Mutual labels:  retrofit
Materialhome
一个基于 Material Design 风格设计的图书展示类App,豆瓣图书,在线电子书。
Stars: ✭ 331 (-38.59%)
Mutual labels:  retrofit
DaMaiProject
大麦界面,实现多种方式网络访问、数据缓存
Stars: ✭ 24 (-95.55%)
Mutual labels:  retrofit
Easyhttp
Android 网络请求框架,简单易用,so easy
Stars: ✭ 423 (-21.52%)
Mutual labels:  retrofit
MockFit
Kotlin library to mock http responses that fits into retrofit
Stars: ✭ 14 (-97.4%)
Mutual labels:  retrofit
Avenging
MVP pattern example on Android: no Dagger or RxJava example
Stars: ✭ 279 (-48.24%)
Mutual labels:  retrofit
Rxretrojsoup
A simple API-like from html website (scrapper) for Android, RxJava2 ready !
Stars: ✭ 492 (-8.72%)
Mutual labels:  retrofit
Androidwithkotlin
🚀 These are android sample projects which are written in Kotlin. It covers video streaming, mp3 player, sqlite, location services, custom camera, o-notifications, simple compass etc.
Stars: ✭ 447 (-17.07%)
Mutual labels:  retrofit
Geeknews
📚A pure reading App based on Material Design + MVP + RxJava2 + Retrofit + Dagger2 + Realm + Glide
Stars: ✭ 3,496 (+548.61%)
Mutual labels:  retrofit

Retrofit For Dart

retrofit retrofit_generator Dart CI CircleCI Build Status

retrofit.dart is a type conversion dio client generator using source_gen and inspired by Chopper and Retrofit.

Usage

Generator

Add the generator to your dev dependencies

dependencies:
  retrofit: any
  logger: any  #for logging purpose

dev_dependencies:
  retrofit_generator: any
  build_runner: any

Define and Generate your API

import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';

part 'example.g.dart';

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

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

@JsonSerializable()
class Task {
  String id;
  String name;
  String avatar;
  String createdAt;

  Task({this.id, this.name, this.avatar, this.createdAt});

  factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
  Map<String, dynamic> toJson() => _$TaskToJson(this);
}

then run the generator

# dart
pub run build_runner build

# flutter	
flutter pub run build_runner build

Use it

import 'package:logger/logger.dart';
import 'package:retrofit_example/example.dart';
import 'package:dio/dio.dart';

final logger = Logger();
void main(List<String> args) {
  final dio = Dio();   // Provide a dio instance
  dio.options.headers["Demo-Header"] = "demo header";   // config your dio headers globally
  final client = RestClient(dio);
  
  client.getTasks().then((it) => logger.i(it));

More

Type Conversion

Before you use the type conversion, please make sure that a factory Task.fromJson(Map<String, dynamic> json) must be provided for each model class. json_serializable is the recommanded to be used as the serialization tool.

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

@JsonSerializable()
class Task {
  String name;
  Task({this.name});
  factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
}

HTTP Methods

The HTTP methods in the below sample are supported.

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

  @GET('/demo')
  Future<String> queries(@Queries() Map<String, dynamic> queries);

  @GET("https://httpbin.org/get")
  Future<String> namedExample(
      @Query("apikey") String apiKey,
      @Query("scope") String scope, 
      @Query("type") String type,
      @Query("from") int from
  );

  @PATCH("/tasks/{id}")
  Future<Task> updateTaskPart(
      @Path() String id, @Body() Map<String, dynamic> map);

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

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

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

  @POST("http://httpbin.org/post")
  Future<void> createNewTaskFromFile(@Part() File file);

  @POST("http://httpbin.org/post")
  @FormUrlEncoded()
  Future<String> postUrlEncodedFormData(@Field() String hello);

Get orignal HTTP reponse

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

  @GET("/tasks")
  Future<HttpResponse<List<Task>>>> getTasks()

HTTP Header

  • Add a HTTP header from the parameter of the method

    	@GET("/tasks")
      Future<Task> getTasks(@Header("Content-Type") String contentType );
    
  • Add staitc HTTP headers

    	@GET("/tasks")
    	@Headers(<String, dynamic>{
    		"Content-Type" : "application/json",
    		"Custom-Header" : "Your header"
    	})
      Future<Task> getTasks();
    

Error Handling

catchError(Object) should be used for capturing the exception and failed response. You can get the detailed response info from DioError.response.

 client.getTask("2").then((it){
   logger.i(it);
 }).catchError((Object obj) {
    // non-200 error goes here.
    switch (obj.runtimeType) {
      case DioError:
        // Here's the sample to get the failed response error code and message
        final res = (obj as DioError).response;
        logger.e("Got error : ${res.statusCode} -> ${res.statusMessage}");
        break;
      default:
    }
  });

}

Multiple endpoints support

If you want to use multiple endpoints to your RestClient, you should pass your base url when you initiate RestClient. Any value defined in RestApi will be ignored.

@RestApi(baseUrl: "this url will be ignored if baseUrl is passed")
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
}

final client = RestClient(dio, baseUrl: "your base url");

If you want to use the base url from dio.option.baseUrl, which has lowest priority, please don't pass any parameter to RestApi annotation and RestClient's structure method.

Hide generated files

For the project not to be confused with the files generated by the retrofit you can hide them.

Android studio

File -> Settings -> Editor -> File Types

Add "ignore files and folders"

*.g.dart

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].