text
stringlengths
1
372
<topic_start>
5. display the response on screen
to display the data on screen, use the
FutureBuilder widget.
the FutureBuilder widget comes with flutter and
makes it easy to work with async data sources.
you must provide two parameters:
note that snapshot.hasData only returns true when
the snapshot contains a non-null data value.
this is why the updateAlbum function should throw an exception
even in the case of a “404 not found” server response.
if updateAlbum returns null then
CircularProgressIndicator will display indefinitely.
<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}');
}
return const CircularProgressIndicator();
},
);
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
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');
}
}
Future<Album> updateAlbum(String title) async {
final response = await http.put(
uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <string, string>{
'content-type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, string>{
'title': title,
}),
);
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 update album.');
}
}
class album {
final int id;
final string title;
const album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'id': int id,
'title': string title,
} =>
album(
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final TextEditingController _controller = TextEditingController();
late Future<Album> _futureAlbum;
@override