text stringlengths 1 372 |
|---|
'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 |
now, use the following steps to update the updateAlbum() |
function to return a Future<Album>: |
<code_start> |
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.'); |
} |
} |
<code_end> |
hooray! |
now you’ve got a function that updates the title of an album. |
<topic_end> |
<topic_start> |
4. get the data from the internet |
get the data from internet before you can update it. |
for a complete example, see the fetch data recipe. |
<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> |
ideally, you will use this method to set |
_futureAlbum during initState to fetch |
the data from the internet. |
<topic_end> |
<topic_start> |
5. update the existing title from user input |
create a TextField to enter a title and a ElevatedButton |
to update the data on 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 |
updateAlbum() method. |
<code_start> |
column( |
mainAxisAlignment: MainAxisAlignment.center, |
children: <widget>[ |
padding( |
padding: const EdgeInsets.all(8), |
child: TextField( |
controller: _controller, |
decoration: const InputDecoration(hintText: 'enter title'), |
), |
), |
ElevatedButton( |
onPressed: () { |
setState(() { |
_futureAlbum = updateAlbum(_controller.text); |
}); |
}, |
child: const Text('Update data'), |
), |
], |
); |
<code_end> |
on pressing the update data button, a network request |
sends the data in the TextField to the server as a PUT request. |
the _futureAlbum variable is used in the next step. |
<topic_end> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.