When apps need to communicate with a server (like getting weather data, user details, or submitting forms), we use networking. Flutter uses the http package to make HTTP requests, and JSON to handle data format.
import 'package:http/http.dart' as http;
import 'dart:convert';
void fetchUserData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users/1'));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print("User Name: \${data['name']}");
} else {
print('Failed to load data');
}
}
http.get fetches the data from the internet.jsonDecode turns JSON string into Dart Map.statusCode to ensure the request succeeded (200 means OK).Think of networking like ordering a pizza. Your app sends a request (order), the server processes it (kitchen), and you get the data back (pizza). JSON is the format in which the pizza details are written (like cheese: yes, size: large).
void sendData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
body: jsonEncode({
'title': 'Hello',
'body': 'Learning Flutter is fun!',
'userId': 1,
}),
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 201) {
print("Post created successfully!");
} else {
print("Failed to create post.");
}
}
http.post is used to send data to a server.'Content-Type' to application/json.Check more on Flutter's Networking Cookbook.