Flutter apps વારંવાર APIs સાથે કમ્યુનિકેટ કરે છે — HTTP રિક્વેસ્ટ્સ કરીને, JSON પાર્સ કરીને, અને રেસ્પોન્સ/errors હેન્ડલ કરીને. http અથવા dio પેકેજીસ, async/await, અને JSON પાર્સિંગ વાપરીને, નેટવર્કિંગ એ મોટાભાગના apps નો મુખ્ય ભાગ છે.
HTTP requests બનાવવા
import 'package:http/http.dart' as http;
// GET request
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
final List data = jsonDecode(response.body); // parse JSON
return data.map((json) => User.fromJson(json)).toList();
} else {
throw Exception('Failed to load users'); // handle errors
}
}
// POST request
await http.post(
Uri.parse('https://api.example.com/users'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'name': 'Ann'}),
);
