API Calls
Fetching data from the internet.
To get data from a REST API, the http package is commonly used. Since network requests are asynchronous, you use FutureBuilder in your UI to handle the different connection states: loading, has data, and has error.
Code Example
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<String> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
return json.decode(response.body)['title'];
} else {
throw Exception('Failed to load data');
}
}
class ApiDataWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return Text('Fetched Title: ${snapshot.data}');
}
return Container(); // Should not happen
},
);
}
}