yudiwbs

Untitled

Apr 7th, 2023
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:http/http.dart' as http;
  3. import 'dart:convert';
  4.  
  5. void main() {
  6. runApp(const MyApp());
  7. }
  8.  
  9. // menampung data hasil pemanggilan API
  10. class Activity {
  11. String aktivitas;
  12. String jenis;
  13.  
  14. Activity({required this.aktivitas, required this.jenis}); //constructor
  15.  
  16. //map dari json ke atribut
  17. factory Activity.fromJson(Map<String, dynamic> json) {
  18. return Activity(
  19. aktivitas: json['activity'],
  20. jenis: json['type'],
  21. );
  22. }
  23. }
  24.  
  25. class MyApp extends StatefulWidget {
  26. const MyApp({Key? key}) : super(key: key);
  27.  
  28. @override
  29. State<StatefulWidget> createState() {
  30. return MyAppState();
  31. }
  32. }
  33.  
  34. class MyAppState extends State<MyApp> {
  35. late Future<Activity> futureActivity; //menampung hasil
  36.  
  37. //late Future<Activity>? futureActivity;
  38. String url = "https://www.boredapi.com/api/activity";
  39.  
  40. Future<Activity> init() async {
  41. return Activity(aktivitas: "", jenis: "");
  42. }
  43.  
  44. //fetch data
  45. Future<Activity> fetchData() async {
  46. final response = await http.get(Uri.parse(url));
  47. if (response.statusCode == 200) {
  48. // jika server mengembalikan 200 OK (berhasil),
  49. // parse json
  50. return Activity.fromJson(jsonDecode(response.body));
  51. } else {
  52. // jika gagal (bukan 200 OK),
  53. // lempar exception
  54. throw Exception('Gagal load');
  55. }
  56. }
  57.  
  58. @override
  59. void initState() {
  60. super.initState();
  61. futureActivity = init();
  62. }
  63.  
  64. @override
  65. Widget build(Object context) {
  66. return MaterialApp(
  67. home: Scaffold(
  68. body: Center(
  69. child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
  70. Padding(
  71. padding: EdgeInsets.only(bottom: 20),
  72. child: ElevatedButton(
  73. onPressed: () {
  74. setState(() {
  75. futureActivity = fetchData();
  76. });
  77. },
  78. child: Text("Saya bosan ..."),
  79. ),
  80. ),
  81. FutureBuilder<Activity>(
  82. future: futureActivity,
  83. builder: (context, snapshot) {
  84. if (snapshot.hasData) {
  85. return Center(
  86. child: Column(
  87. mainAxisAlignment: MainAxisAlignment.center,
  88. children: [
  89. Text(snapshot.data!.aktivitas),
  90. Text("Jenis: ${snapshot.data!.jenis}")
  91. ]));
  92. } else if (snapshot.hasError) {
  93. return Text('${snapshot.error}');
  94. }
  95. // default: loading spinner.
  96. return const CircularProgressIndicator();
  97. },
  98. ),
  99. ]),
  100. ),
  101. ));
  102. }
  103. }
  104.  
Add Comment
Please, Sign In to add comment