text
stringlengths
1
372
alignment: alignment.center,
padding: const EdgeInsets.all(8),
child: (_futurealbum == null) ? buildColumn() : buildFutureBuilder(),
),
),
);
}
column buildColumn() {
return 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'),
),
],
);
}
FutureBuilder<Album> buildFutureBuilder() {
return 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>
update data over the internet
updating data over the internet is necessary for most apps.
the http package has got that covered!
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
to add the http package as a dependency,
run flutter pub add:
import the http package.
<code_start>
import 'package:http/http.dart' as http;
<code_end>
<topic_end>
<topic_start>
2. updating data over the internet using the http package
this recipe covers how to update an album title to the
JSONPlaceholder using the http.put() method.
<code_start>
Future<http.Response> updateAlbum(String title) {
return 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,
}),
);
}
<code_end>
the http.put() 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,