flutter http get json to map
To make an HTTP GET request and convert the received JSON to a map in Flutter, you can use the http
package along with the convert
package. Here's an example:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<Map<String, dynamic>> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to fetch data');
}
}
void main() async {
try {
Map<String, dynamic> data = await fetchData();
// Use the 'data' map here
} catch (e) {
// Handle the exception
}
}
In this example, we import the http
package and the convert
package. The fetchData
function sends an HTTP GET request to the specified URL and checks the response's status code. If the status code is 200 (indicating a successful request), the response body is decoded from JSON using json.decode
and returned as a map. If the status code is not 200, an exception is thrown.
In the main
function, we call the fetchData
function and await the result. The returned map can then be used for further processing. Any exceptions thrown during the process can be caught and handled accordingly.
Remember to replace 'https://api.example.com/data'
with the actual URL you want to fetch JSON data from.