text stringlengths 1 372 |
|---|
for information on how to test this functionality, |
see the following recipes: |
<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'); |
} |
} |
class album { |
final int userId; |
final int id; |
final string title; |
const album({ |
required this.userId, |
required this.id, |
required this.title, |
}); |
factory Album.fromJson(Map<String, dynamic> json) { |
return switch (json) { |
{ |
'userid': int userId, |
'id': int id, |
'title': string title, |
} => |
album( |
userId: userId, |
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() => _MyAppState(); |
} |
class _MyAppState extends State<MyApp> { |
late Future<Album> futureAlbum; |
@override |
void initState() { |
super.initState(); |
futureAlbum = fetchAlbum(); |
} |
@override |
widget build(BuildContext context) { |
return MaterialApp( |
title: 'fetch data example', |
theme: ThemeData( |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), |
), |
home: scaffold( |
appBar: AppBar( |
title: const Text('Fetch data example'), |
), |
body: center( |
child: FutureBuilder<Album>( |
future: futureAlbum, |
builder: (context, snapshot) { |
if (snapshot.hasdata) { |
return text(snapshot.data!.title); |
} else if (snapshot.haserror) { |
return text('${snapshot.error}'); |
} |
// by default, show a loading spinner. |
return const CircularProgressIndicator(); |
}, |
), |
), |
), |
); |
} |
} |
<code_end> |
<topic_end> |
<topic_start> |
make authenticated requests |
to fetch data from most web services, you need to provide |
authorization. there are many ways to do this, |
but perhaps the most common uses the authorization HTTP header. |
<topic_end> |
<topic_start> |
add authorization headers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.