fetchJson method
Fetches and decodes JSON data from the URL represented by this string.
This method assumes that the string is a valid URL.
It performs an HTTP GET request to the specified URL,
then decodes the response body as JSON using json.decode.
Example
final jsonData = await 'https://api.example.com/data'.fetchJson();
print(jsonData['key']);
Returns
A Future<dynamic> that completes with the decoded JSON object,
which could be a Map<String, dynamic> or a List, depending on the response.
Throws
- FormatException if the response body is not valid JSON.
http.ClientExceptionor other exceptions if the HTTP request fails.
Implementation
Future<dynamic> fetchJson() async {
final response = await http.get(Uri.parse(this));
// You may optionally want to check status code here before decoding
// For example:
// if (response.statusCode != 200) {
// throw Exception('Failed to load JSON: ${response.statusCode}');
// }
return json.decode(response.body);
}