hmawla

Untitled

Jul 5th, 2021 (edited)
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.90 KB | None | 0 0
  1. const baseUrl = "your url";
  2.  
  3. class ApiClient {
  4.   Dio _dio;
  5.  
  6.   ApiClient() {
  7.     BaseOptions options = new BaseOptions(
  8.       baseUrl: baseUrl,
  9.       connectTimeout: 20000,
  10.       receiveTimeout: 30000,
  11.       responseType: ResponseType.json,
  12.       headers: {'accept': 'application/json'},
  13.     );
  14.     _dio = new Dio(options);
  15.  
  16.     _dio.interceptors
  17.         .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
  18.       logger.i('${options.method}: ${options.uri}');
  19.       return options;
  20.     }, onResponse: (Response response) async {
  21.       logger.i(
  22.           '(${response.statusCode}) ${response.request.method}: ${response.request.uri} \n ${response.data}');
  23.       return response; // continue
  24.     }, onError: (DioError e) async {
  25.       if (e.response != null) {
  26.         logger.e(
  27.             '(${e.response.statusCode}) ${e.response.request.method}: ${e.response.request.uri} \n ${e.response.data}');
  28.       } else {
  29.         logger.e(e);
  30.       }
  31.       return e; //continue
  32.     }));
  33.   }
  34.  
  35.   Future<User> createUser(username, password) async {
  36.     try {
  37.       Response response = await _dio.request(
  38.         "/user",
  39.         data: {
  40.             'username': username,
  41.             'password': password
  42.         },
  43.         options: Options(
  44.           method: "POST",
  45.         ),
  46.       );
  47.       return Transaction.fromMap(response.data);
  48.     } catch (error) {
  49.       throw error;
  50.     }
  51.   }
  52. }
  53.  
  54. //Usage
  55.  
  56. createUserExampleMethod() {
  57.     ApiClient apiClient= new ApiClient();
  58.     apiClient.createUser(username: '', password: '')
  59.           .then((User user) {
  60.             //You got yourself a user model here
  61.           }
  62. }
  63.  
  64. //User Model Example
  65.  
  66. class User {
  67.   String id;
  68.   String username;
  69.  
  70.  
  71.   User(
  72.     this.id,
  73.     this.username,
  74.   );
  75.  
  76.   User.name(
  77.     this.id,
  78.     this.username,
  79.   );
  80.  
  81.   User.fromMap(Map<String, dynamic> user) {
  82.     this.id = user['id'];
  83.     this.username= user['username'];
  84.   }
  85. }
Add Comment
Please, Sign In to add comment