text
stringlengths
1
372
);
}
<code_end>
the http.post() method returns a future that contains a response.
<topic_end>
<topic_start>
3. convert the http.Response to 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 with pattern matching is only one option.
for more information, see the full article on
JSON and serialization.
<code_start>
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.'),
};
}
}
<code_end>
<topic_end>
<topic_start>
convert the http.Response to an album
use the following steps to update the createAlbum()
function to return a Future<Album>:
<code_start>
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.');
}
}
<code_end>
hooray! now you’ve got a function that sends the title to a
server to create an album.
<topic_end>
<topic_start>
4. get a title from user input
next, create a TextField to enter a title and
a ElevatedButton to send data to server.
also define a TextEditingController to read the
user input from a TextField.
when the ElevatedButton is pressed, the _futureAlbum
is set to the value returned by createAlbum() method.
<code_start>
column(
mainAxisAlignment: MainAxisAlignment.center,
children: <widget>[
TextField(
controller: _controller,
decoration: const InputDecoration(hintText: 'enter title'),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = createAlbum(_controller.text);
});
},
child: const Text('Create data'),
),
],
)
<code_end>
on pressing the create data button, make the network request,
which sends the data in the TextField to the server