Created
November 25, 2022 12:01
-
-
Save NizarETH/5f59d6b9cd27cbf9c276fd4dc22abd37 to your computer and use it in GitHub Desktop.
Request Http Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} 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 Album( | |
userId: json['userId'], | |
id: json['id'], | |
title: json['title'], | |
); | |
} | |
} | |
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( | |
primarySwatch: Colors.blue, | |
), | |
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(); | |
}, | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment