text
stringlengths
1
372
as a POST request.
the future, _futureAlbum, is used in the next step.
<topic_end>
<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 asynchronous 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 createAlbum() function should throw an exception
even in the case of a “404 not found” server response.
if createAlbum() returns null, then
CircularProgressIndicator displays 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> createAlbum(String title) async {
final response = await http.post(
uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <string, string>{
'content-type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, string>{
'title': title,
}),
);
if (response.statuscode == 201) {
// if the server did return a 201 CREATED response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// if the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to create 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();
Future<Album>? _futureAlbum;
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'create data example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: scaffold(
appBar: AppBar(
title: const Text('Create data example'),
),
body: container(