[dart] Code

Viewer

  1. import 'dart:async';
  2. import 'dart:convert';
  3.  
  4. import 'package:flutter/material.dart';
  5. import 'package:http/http.dart' as http;
  6.  
  7. Future<Album> fetchAlbum() async {
  8.   final response = await http.get(Uri.parse(
  9.       'http://localhost:8000/api/users'));
  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));
  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.  
  22. class Album {
  23.   final int id;
  24.   final String nama;
  25.   final String alamat;
  26.  
  27.   Album({
  28.     required this.id,
  29.     required this.nama,
  30.     required this.alamat,
  31.   });
  32.  
  33.   factory Album.fromJson(Map<String, dynamic> json) {
  34.     return Album(
  35.       id: json['id'],
  36.       nama: json['nama'],
  37.       alamat: json['alamat'],
  38.     );
  39.   }
  40. }
  41.  
  42. void main() => runApp(MyApp());
  43.  
  44. class MyApp extends StatefulWidget {
  45.   MyApp({Key? key}) : super(key: key);
  46.  
  47.   @override
  48.   _MyAppState createState() => _MyAppState();
  49. }
  50.  
  51. class _MyAppState extends State<MyApp> {
  52.   late Future<Album> futureAlbum;
  53.  
  54.   @override
  55.   void initState() {
  56.     super.initState();
  57.     futureAlbum = fetchAlbum();
  58.   }
  59.  
  60.   @override
  61.   Widget build(BuildContext context) {
  62.     return MaterialApp(
  63.       title: 'Fetch Data Example',
  64.       theme: ThemeData(
  65.         primarySwatch: Colors.blue,
  66.       ),
  67.       home: Scaffold(
  68.         appBar: AppBar(
  69.           title: Text('Fetch Data Example'),
  70.         ),
  71.         body: Center(
  72.           child: FutureBuilder<Album>(
  73.             future: futureAlbum,
  74.             builder: (context, snapshot) {
  75.               if (snapshot.hasData) {
  76.                 return Text(snapshot.data!.nama);
  77.               } else if (snapshot.hasError) {
  78.                 return Text("${snapshot.error}");
  79.               }
  80.  
  81.               // By default, show a loading spinner.
  82.               return CircularProgressIndicator();
  83.             },
  84.           ),
  85.         ),
  86.       ),
  87.     );
  88.   }
  89. }
  90.  

Editor

You can edit this paste and save as new: