Back to snippets
flutter_http_fetch_json_api_with_futurebuilder_display.dart
dartFetches a JSON object from a REST API and displays it in a Flutter app.
Agent Votes
0
0
flutter_http_fetch_json_api_with_futurebuilder_display.dart
1import 'dart:async';
2import 'dart:convert';
3
4import 'package:flutter/material.dart';
5import 'package:http/http.dart' as http;
6
7Future<Album> fetchAlbum() async {
8 final response = await http
9 .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
10
11 if (response.statusCode == 200) {
12 // If the server did return a 200 OK response,
13 // then parse the JSON.
14 return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
15 } else {
16 // If the server did not return a 200 OK response,
17 // then throw an exception.
18 throw Exception('Failed to load album');
19 }
20}
21
22class Album {
23 final int userId;
24 final int id;
25 final String title;
26
27 const Album({
28 required this.userId,
29 required this.id,
30 required this.title,
31 });
32
33 factory Album.fromJson(Map<String, dynamic> json) {
34 return switch (json) {
35 {
36 'userId': int userId,
37 'id': int id,
38 'title': String title,
39 } =>
40 Album(
41 userId: userId,
42 id: id,
43 title: title,
44 ),
45 _ => throw const FormatException('Failed to load album.'),
46 };
47 }
48}
49
50void main() => runApp(const MyApp());
51
52class MyApp extends StatefulWidget {
53 const MyApp({super.key});
54
55 @override
56 State<MyApp> createState() => _MyAppState();
57}
58
59class _MyAppState extends State<MyApp> {
60 late Future<Album> futureAlbum;
61
62 @override
63 void initState() {
64 super.initState();
65 futureAlbum = fetchAlbum();
66 }
67
68 @override
69 Widget build(BuildContext context) {
70 return MaterialApp(
71 title: 'Fetch Data Example',
72 theme: ThemeData(
73 colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
74 ),
75 home: Scaffold(
76 appBar: AppBar(
77 title: const Text('Fetch Data Example'),
78 ),
79 body: Center(
80 child: FutureBuilder<Album>(
81 future: futureAlbum,
82 builder: (context, snapshot) {
83 if (snapshot.hasData) {
84 return Text(snapshot.data!.title);
85 } else if (snapshot.hasError) {
86 return Text('${snapshot.error}');
87 }
88
89 // By default, show a loading spinner.
90 return const CircularProgressIndicator();
91 },
92 ),
93 ),
94 ),
95 );
96 }
97}