Last active
February 13, 2022 02:15
-
-
Save humblerookie/1d70190aa8aa0901ae437ad21c5b3955 to your computer and use it in GitHub Desktop.
Dio Built Value Json Decoder/Transformer for Dart/Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:my_app/data_model/serializers.dart'; | |
import 'package:flutter/foundation.dart'; | |
Future<T> decodeJson<T>(String res) async { | |
var list = List(); | |
list.add(res); | |
list.add(T); | |
//Replace compute with spawning any other isolate, compute is simpler abstraction of isolate api. | |
var result = await compute(_decode, list); | |
return result; | |
} | |
dynamic _decode(List list) { | |
var decoded = json.decode(list[0]); | |
var matchedDecoder = serializers.serializerForType(list[1]); | |
if (matchedDecoder != null) { | |
return serializers.deserializeWith(matchedDecoder, decoded); | |
} else { | |
return null; | |
} | |
} | |
// Sample usage | |
/* | |
Future<User> getUser() async { | |
try { | |
Response<String> response = await _dio.get("/me"); | |
var userResponse = await decodeJson<User>(response.data); | |
return userResponse; | |
} catch (error, stacktrace) { | |
print(stacktrace); | |
return null; | |
} | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment