Flutter: DateTime as argument in retrofit method; DateTime ISO 8061 serialization; Retrofit date iso8061 formatting
649
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.
Author by
kosiara - Bartosz Kosarzycki
Updated on December 28, 2022Comments
-
kosiara - Bartosz Kosarzycki over 1 year
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?
-
Akbar Pulatov about 2 yearsthis answer should be chosen.
-
Stacky almost 2 yearsOn the one hand, it's good that it can be fixed that easily. On the other hand, why is Retrofit generating this defective code in the first place?