Flutter: DateTime as argument in retrofit method; DateTime ISO 8061 serialization; Retrofit date iso8061 formatting

Viewed 555

I want to define a method as following:

@GET("/users")
@Headers(<String, dynamic>{"Accept": "application/json", "Authorization": "Basic " + authKey})
Future<List<User>> getUsers(@Query("fromDate") DateTime from, @Query("toDate") DateTime to);

So that the DateTime parameters are serialized to ISO8061 format and the output query looks like the following:

[GET] https://address.com/users?fromDate=2021-02-21T12:00:00.000Z&toDate=2021-02-27T12:00:00.000Z

I'm already using Flutter retrofit lib (which internally utilizes Flutter dio).

How can I do this?

1 Answers

Just use an extension method like the following. Flutter has 8061 DateTime serialization built in!

extension Iso8061SerializableDateTime on DateTime {
  String toJson() => this.toIso8601String();
}

Insight:

Retrofit generates the following method in *.g.dart file:

  @override
  Future<List<User>> getUsers(from, to) async {
    final queryParameters = <String, dynamic>{
      r'fromDate': from?.toJson(),
      r'toDate': to?.toJson()
    };
    final _data = <String, dynamic>{};
    final _result = await _dio.request<List<dynamic>>('/orders',
        queryParameters: queryParameters,
        options: RequestOptions( ... )
    )

which needs .toJson() method that we're proving with an extension method. That's all.

Related