forked from md-siam/package_of_the_day
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.dart
100 lines (93 loc) · 2.93 KB
/
http.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // perform http request
import 'dart:convert'; // convert response string to JSON (map)
class MyHTTP extends StatefulWidget {
const MyHTTP({Key? key}) : super(key: key);
@override
State<MyHTTP> createState() => _MyHTTPState();
}
class _MyHTTPState extends State<MyHTTP> {
String data = "";
String title = "";
final url = Uri.parse('https://jsonplaceholder.typicode.com/albums/1');
bool isLoading = false;
performHTTPRequest() async {
String output = "";
try {
final response = await http.get(url);
debugPrint('Status code: ${response.statusCode}');
//http://192.168.0.27:5500/messages.json
if (response.statusCode == 200) {
output = response.body;
var json = jsonDecode(output);
setState(() {
data = output;
title = json['title'];
isLoading = false;
});
debugPrint('Body: ${response.body}');
} else {
throw Exception('Failed to load data');
}
return output;
} catch (e) {
// ignore: avoid_print
print("Error: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('HTTP Request')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'::: HTTP Response :::\n',
style: Theme.of(context).textTheme.headline6,
),
!isLoading
? Text(
data,
style: const TextStyle(fontSize: 16, color: Colors.teal),
)
: const SizedBox(child: CircularProgressIndicator()),
const SizedBox(height: 60),
Text(
'\n::: The JSON title attribute :::\n',
style: Theme.of(context).textTheme.headline6,
),
!isLoading
? Text(
title,
style: const TextStyle(fontSize: 16, color: Colors.red),
)
: const SizedBox(child: CircularProgressIndicator()),
const SizedBox(height: 70),
ElevatedButton(
onPressed: () async {
setState(() => isLoading = true);
performHTTPRequest();
/// if `performHTTPRequest()` is not responding
///
await Future.delayed(const Duration(seconds: 3));
setState(() => isLoading = false);
},
child: const Text('GET DATA FROM HTTP REQUEST'),
),
ElevatedButton(
child: const Text('RESET'),
onPressed: () {
setState(() {
data = "";
title = "";
});
},
)
],
),
),
);
}
}