|
| 1 | +import 'dart:convert'; |
| 2 | + |
| 3 | +import 'package:exercise/models/user.dart'; |
| 4 | +import 'package:flutter/material.dart'; |
| 5 | +import 'package:http/http.dart' as http; |
| 6 | + |
| 7 | +class Home extends StatelessWidget { |
| 8 | + @override |
| 9 | + Widget build(BuildContext context) { |
| 10 | + return Scaffold( |
| 11 | + appBar: _appBar(), |
| 12 | + body: _body(), |
| 13 | + ); |
| 14 | + } |
| 15 | + |
| 16 | + AppBar _appBar() { |
| 17 | + return AppBar( |
| 18 | + title: const Text("D Tree Exercise"), |
| 19 | + ); |
| 20 | + } |
| 21 | + |
| 22 | + Future<List<User>> _future() async { |
| 23 | + final response = await http.get( |
| 24 | + Uri.parse('https://exercise-646d.restdb.io/rest/group-1'), |
| 25 | + headers: { |
| 26 | + 'x-apikey': '5c5c7076f210985199db5488', |
| 27 | + }, |
| 28 | + ); |
| 29 | + |
| 30 | + if (response.statusCode == 200) { |
| 31 | + return (json.decode(response.body) as List) |
| 32 | + .map((i) => User.fromJson(i)) |
| 33 | + .toList(); |
| 34 | + } else { |
| 35 | + throw Exception('Failed to load users'); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + Widget _body() { |
| 40 | + return FutureBuilder<List<User>>( |
| 41 | + future: _future(), |
| 42 | + builder: (context, snapshot) { |
| 43 | + if (snapshot.hasData) { |
| 44 | + return _listView(snapshot.data); |
| 45 | + } |
| 46 | + |
| 47 | + if (snapshot.hasError) { |
| 48 | + return _showError(snapshot.error.toString()); |
| 49 | + } |
| 50 | + |
| 51 | + return _showLoading(); |
| 52 | + }, |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + Widget _showError(String message) { |
| 57 | + return Center( |
| 58 | + child: Text(message), |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + Widget _showLoading() { |
| 63 | + return Center( |
| 64 | + child: const CircularProgressIndicator(), |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + Widget _listView(List<User> users) { |
| 69 | + return ListView.builder( |
| 70 | + padding: const EdgeInsets.all(8.0), |
| 71 | + itemCount: users.length, |
| 72 | + itemBuilder: (context, index) { |
| 73 | + return _listItem(users[index]); |
| 74 | + }, |
| 75 | + ); |
| 76 | + } |
| 77 | + |
| 78 | + Card _listItem(User user) { |
| 79 | + return Card( |
| 80 | + child: Padding( |
| 81 | + padding: const EdgeInsets.all(8.0), |
| 82 | + child: Column( |
| 83 | + crossAxisAlignment: CrossAxisAlignment.start, |
| 84 | + children: [ |
| 85 | + Text("Name: ${user.name}"), |
| 86 | + Text("Surname: ${user.surname}"), |
| 87 | + Text("Age: ${user.age}"), |
| 88 | + Text("City: ${user.city}"), |
| 89 | + ], |
| 90 | + ), |
| 91 | + ), |
| 92 | + ); |
| 93 | + } |
| 94 | +} |
0 commit comments