Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const baseUrl = "your url";
- class ApiClient {
- Dio _dio;
- ApiClient() {
- BaseOptions options = new BaseOptions(
- baseUrl: baseUrl,
- connectTimeout: 20000,
- receiveTimeout: 30000,
- responseType: ResponseType.json,
- headers: {'accept': 'application/json'},
- );
- _dio = new Dio(options);
- _dio.interceptors
- .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
- logger.i('${options.method}: ${options.uri}');
- return options;
- }, onResponse: (Response response) async {
- logger.i(
- '(${response.statusCode}) ${response.request.method}: ${response.request.uri} \n ${response.data}');
- return response; // continue
- }, onError: (DioError e) async {
- if (e.response != null) {
- logger.e(
- '(${e.response.statusCode}) ${e.response.request.method}: ${e.response.request.uri} \n ${e.response.data}');
- } else {
- logger.e(e);
- }
- return e; //continue
- }));
- }
- Future<User> createUser(username, password) async {
- try {
- Response response = await _dio.request(
- "/user",
- data: {
- 'username': username,
- 'password': password
- },
- options: Options(
- method: "POST",
- ),
- );
- return Transaction.fromMap(response.data);
- } catch (error) {
- throw error;
- }
- }
- }
- //Usage
- createUserExampleMethod() {
- ApiClient apiClient= new ApiClient();
- apiClient.createUser(username: '', password: '')
- .then((User user) {
- //You got yourself a user model here
- }
- }
- //User Model Example
- class User {
- String id;
- String username;
- User(
- this.id,
- this.username,
- );
- User.name(
- this.id,
- this.username,
- );
- User.fromMap(Map<String, dynamic> user) {
- this.id = user['id'];
- this.username= user['username'];
- }
- }
Add Comment
Please, Sign In to add comment