[dart] Code
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- 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(
- 'http://localhost:8000/api/users'));
- 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 id;
- final String nama;
- final String alamat;
- Album({
- required this.id,
- required this.nama,
- required this.alamat,
- });
- factory Album.fromJson(Map<String, dynamic> json) {
- return Album(
- id: json['id'],
- nama: json['nama'],
- alamat: json['alamat'],
- );
- }
- }
- void main() => runApp(MyApp());
- class MyApp extends StatefulWidget {
- MyApp({Key? key}) : super(key: key);
- @override
- _MyAppState 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: Text('Fetch Data Example'),
- ),
- body: Center(
- child: FutureBuilder<Album>(
- future: futureAlbum,
- builder: (context, snapshot) {
- if (snapshot.hasData) {
- return Text(snapshot.data!.nama);
- } else if (snapshot.hasError) {
- return Text("${snapshot.error}");
- }
- // By default, show a loading spinner.
- return CircularProgressIndicator();
- },
- ),
- ),
- ),
- );
- }
- }
Editor
You can edit this paste and save as new:
File Description
- Code
- Paste Code
- 24 Jul-2021
- 2.06 Kb
You can Share it:
Latest Code Pastes