yudiwbs

flutter_listviewbuilder_http

May 23rd, 2022
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 4.09 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:http/http.dart' as http;
  3. import 'dart:convert';
  4.  
  5. /*
  6.    
  7.    {"data":[{"ID Nation":"01000US","Nation":"United States",
  8.    "ID Year":2019,"Year":"2019","Population":328239523,"Slug Nation":"united-states"},
  9.    {"ID Nation":"01000US","Nation":"United States","ID Year":2018,"Year":"2018","Population":327167439,
  10.    "Slug Nation":"united-states"},{"ID Nation":"01000US","Nation":"United States","ID
  11.    ….
  12.     Year":2014,"Year":"2014","Population":318857056,"Slug Nation":"united-states"},
  13.     {"ID Nation":"01000US","Nation":"United States","ID Year":2013,"Year":"2013",
  14.     "Population":316128839,"Slug Nation":"united-states"}],
  15.     "source":
  16.     [{"measures":["Population"],"annotations":
  17.     { ... },"name":"acs_yg_total_population_1","substitutions":[]}]}
  18.  
  19. */
  20.  
  21. class PopulasiTahun {
  22.   int tahun;
  23.   int populasi;
  24.   PopulasiTahun({required this.tahun, required this.populasi});
  25. }
  26.  
  27. class Populasi {
  28.   List<PopulasiTahun> ListPop = <PopulasiTahun>[];
  29.  
  30.   Populasi(Map<String, dynamic> json) {
  31.     // isi listPop disini
  32.     var data = json["data"];
  33.     for (var val in data) {
  34.       var tahun = int.parse(val["Year"]); //thn dijadikan int
  35.       var populasi = val["Population"]; //pouliasi sudah int
  36.       ListPop.add(PopulasiTahun(tahun: tahun, populasi: populasi));
  37.     }
  38.   }
  39.   //map dari json ke atribut
  40.   factory Populasi.fromJson(Map<String, dynamic> json) {
  41.     return Populasi(json);
  42.   }
  43. }
  44.  
  45. void main() {
  46.   runApp(MyApp());
  47. }
  48.  
  49. class MyApp extends StatefulWidget {
  50.   @override
  51.   State<StatefulWidget> createState() {
  52.     return MyAppState();
  53.   }
  54. }
  55.  
  56. //class state
  57. class MyAppState extends State<MyApp> {
  58.   late Future<Populasi> futurePopulasi;
  59.  
  60.   //https://datausa.io/api/data?drilldowns=Nation&measures=Population
  61.   String url =
  62.       "https://datausa.io/api/data?drilldowns=Nation&measures=Population";
  63.  
  64.   //fetch data
  65.   Future<Populasi> fetchData() async {
  66.     final response = await http.get(Uri.parse(url));
  67.  
  68.     if (response.statusCode == 200) {
  69.       // jika server mengembalikan 200 OK (berhasil),
  70.       // parse json
  71.       return Populasi.fromJson(jsonDecode(response.body));
  72.     } else {
  73.       // jika gagal (bukan  200 OK),
  74.       // lempar exception
  75.       throw Exception('Gagal load');
  76.     }
  77.   }
  78.  
  79.   @override
  80.   void initState() {
  81.     super.initState();
  82.     futurePopulasi = fetchData();
  83.   }
  84.  
  85.   @override
  86.   Widget build(BuildContext context) {
  87.     return MaterialApp(
  88.         title: 'coba http',
  89.         home: Scaffold(
  90.           appBar: AppBar(
  91.             title: const Text('coba http'),
  92.           ),
  93.           body: Center(
  94.             child: FutureBuilder<Populasi>(
  95.               future: futurePopulasi,
  96.               builder: (context, snapshot) {
  97.                 if (snapshot.hasData) {
  98.                   return Center(
  99.                     //gunakan listview builder
  100.                     child: ListView.builder(
  101.                       itemCount: snapshot
  102.                           .data!.ListPop.length, //asumsikan data ada isi
  103.                       itemBuilder: (context, index) {
  104.                         return Container(
  105.                             decoration: BoxDecoration(border: Border.all()),
  106.                             padding: const EdgeInsets.all(14),
  107.                             child: Column(
  108.                                 mainAxisAlignment: MainAxisAlignment.center,
  109.                                 children: [
  110.                                   Text(snapshot.data!.ListPop[index].tahun
  111.                                       .toString()),
  112.                                   Text(snapshot.data!.ListPop[index].populasi
  113.                                       .toString()),
  114.                                 ]));
  115.                       },
  116.                     ),
  117.                   );
  118.                 } else if (snapshot.hasError) {
  119.                   return Text('${snapshot.error}');
  120.                 }
  121.                 // By default, show a loading spinner.
  122.                 return const CircularProgressIndicator();
  123.               },
  124.             ),
  125.           ),
  126.         ));
  127.   }
  128. }
  129.  
Add Comment
Please, Sign In to add comment