Introduction
API calls let your app get fresh information from the internet. This helps your app show the latest data without needing to update the app itself.
API calls let your app get fresh information from the internet. This helps your app show the latest data without needing to update the app itself.
final response = await http.get(Uri.parse('https://example.com/data')); if (response.statusCode == 200) { var data = jsonDecode(response.body); // use data }
http package to make API calls in Flutter.statusCode to make sure the call worked.final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) { var jsonData = jsonDecode(response.body); }
This app fetches a to-do item title from a remote API and shows it on the screen. It starts with 'Loading...' and updates when data arrives.
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _title = 'Loading...'; @override void initState() { super.initState(); fetchTitle(); } Future<void> fetchTitle() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1')); if (response.statusCode == 200) { final data = jsonDecode(response.body); setState(() { _title = data['title']; }); } else { setState(() { _title = 'Failed to load'; }); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('API Call Example')), body: Center(child: Text(_title, style: TextStyle(fontSize: 24))), ), ); } }
API calls can take time, so use async/await to avoid freezing the app.
Always handle errors like network failures gracefully.
Use JSON decoding to convert the response into usable data.
API calls get fresh data from the internet for your app.
Use async calls and check response status to handle data safely.
Parsing JSON lets you use the data inside your app easily.
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data['name']);
} else {
print('Error');
}var response = http.get(Uri.parse(url));
if (response.statusCode == 200) {
print('Success');
}Pass the test and this pattern moves unknown