How to dynamic base dio request
Tags: flutter, dart, mobile
Published: 2023-06-04 07:56:29

Do you feel inconvenient in implementing the request to server by using dio library or http in flutter? With my expirience, everytime i want to use new api for get data or post data to server, i have to rewrite the code again, but after that the data i received from server is json type so i have to convert it from json to data type which i want to transfer. So now, i have implemented successfully the base request to optimize code for requesting simply. And i want to share with you. If it can help you, it is my pleasure. So let start now.
I hope you sympathize with my writing skill.

In this blog, may be i miss the explanation about dio library or http request to server. If you want to understand more about it. You can relevant to the doc in pub.dev website as i link below. In this example, i import dio version 5.1.2.

Link dio library: https://pub.dev/packages/dio

```
dio: ^5.2.0
```

## Base Dio
First of all, I create the base_dio.dart with the abstract class to handle the request. Below is my example about:

```
abstract class BaseDio {
static String hostName = 'http://localhost:3000';

final dio = Dio();

}
```

## Map json model
After that you have to create the map for identifying with the transfer from json to model.
```
Map<Type, Type Function(Map<String, dynamic> json)> temp = {
    User: User.fromJson
  };
```

## Create model extending Type class
Type is the type data of model you want to transfer. As my example above, i implement the user model class extending from type. I will show you my model as below.
```
class User extends Type {
  final String name;

  User({this.name = ''});

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: (json['name'] as String?) ?? '',
      );

  @override
  String toString() {
    return 'Users : $name';
  }
}
```
When we set up the map for identifying the model class and convert from json to model, we have to one method to handle this transformation. And below is my solution:
```
T? tranformModel<T extends Type>(T type, dynamic json) {
    final typeFunc = temp[type];
    if (typeFunc != null) {
      return typeFunc(json as Map<String, dynamic>) as T;
    } else {
      return null;
    }
  }
```
So now, it is the time to execute the request server, i will show you how to handle the get request. It is the function which help you to implement request to server.
```
Future<T?> getData<T extends Type>(
    String api, {
    Object? data,
    Map<String, dynamic>? queryParam,
  }) async {
    final response = await dio.get<Map<String, dynamic>>(
      hostName + api,
      data: data,
      queryParameters: queryParam,
    );
    if (response.statusCode == 200 && response.data!['response'] == 'oke') {
      return tranformModel(T, response.data!['data']) as T;
    } else {
      throw Exception();
    }
  }
```
Let start to implement base_dio with the class. In this case, I just named it as dio_api.dart like below.
```
class DioApi extends BaseDio {
  Future<User?> getUser() => getData<User>('/');
}
```
At last, i will show the result with my base dio work or not. I call the my localhost:3000 request to test my function.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kk25cvccucll7x4nmor.png)

Conclusion
Overview, I have shown you how to create the class to handle the dynamic transfer from Json to model class. I hope this will help you. If you have any problem, you can check my project over the below link to understand more. 
https://github.com/tuyen3962/demo_base_dio

Thank you