Networking & JSON in Flutter

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.

Keyword Explanation:

🌐 Making a Simple GET Request

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');
  }
}
    
Important:

🧠 Real World Analogy

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).

🔁 POST Request Example (Sending Data)

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.");
  }
}
    
Tip:

Check more on Flutter's Networking Cookbook.