text
stringlengths
1
474
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}<code_end>
The http.get() method returns a Future that contains a Response.<topic_end>
<topic_start>
3. Convert the response into a custom Dart object
While it’s easy to make a network request, working with a raw
Future<http.Response> isn’t very convenient.
To make your life easier,
convert the http.Response into a Dart object.<topic_end>
<topic_start>
Create an Album class
First, create an Album class that contains the data from the
network request. It includes a factory constructor that
creates an Album from JSON.Converting JSON using pattern matching is only one option.
For more information, see the full article on
JSON and serialization.
<code_start>class Album {
final int userId;
final int id;
final String title;
const Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'userId': int userId,
'id': int id,
'title': String title,
} =>
Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}<code_end>
<topic_end>
<topic_start>
Convert the http.Response to an Album
Now, use the following steps to update the fetchAlbum()
function to return a Future<Album>:
<code_start>Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}<code_end>
Hooray!
Now you’ve got a function that fetches an album from the internet.<topic_end>
<topic_start>
4. Fetch the data
Call the fetchAlbum() method in either the
initState() or didChangeDependencies()
methods.The initState() method is called exactly once and then never again.
If you want to have the option of reloading the API in response to an
InheritedWidget changing, put the call into the
didChangeDependencies() method.
See State for more details.
<code_start>class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
// ···
}<code_end>
This Future is used in the next step.<topic_end>
<topic_start>
5. Display the data
To display the data on screen, use the
FutureBuilder widget.
The FutureBuilder widget comes with Flutter and
makes it easy to work with asynchronous data sources.You must provide two parameters:Note that snapshot.hasData only returns true
when the snapshot contains a non-null data value.Because fetchAlbum can only return non-null values,
the function should throw an exception
even in the case of a “404 Not Found” server response.
Throwing an exception sets the snapshot.hasError to true
which can be used to display an error message.Otherwise, the spinner will be displayed.
<code_start>FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.