/
pull_to_refresh.dart
87 lines (77 loc) · 2.29 KB
/
pull_to_refresh.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
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class SwipeToRefreshExample extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _SwipeToRefreshState();
}
}
class _SwipeToRefreshState extends State<SwipeToRefreshExample> {
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
GlobalKey<RefreshIndicatorState>();
User user = User(
"Default User",
"https://www.bsn.eu/wp-content/uploads/2016/12/user-icon-image-placeholder-300-grey.jpg",
);
@override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => _refreshIndicatorKey.currentState?.show());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Swipe To Refresh"),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Refresh',
onPressed: () {
_refreshIndicatorKey.currentState?.show();
}),
],
),
body: RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: _refresh,
child: ListView(children: [
Padding(
padding: const EdgeInsets.only(top: 24),
child: Center(
child: Column(
children: <Widget>[
Image.network(user.image, height: 128, width: 128),
SizedBox(height: 24),
Text(user.name),
],
),
),
)
])),
);
}
Future<User> getUser() async {
final response = await http.get(Uri.parse("https://randomuser.me/api/"));
final responseJson = json.decode(response.body);
return User.fromJson(responseJson);
}
Future<Null> _refresh() {
return getUser().then((_user) {
setState(() => user = _user);
});
}
}
class User {
final String name, image;
User(this.name, this.image);
factory User.fromJson(Map<String, dynamic> json) {
json = json['results'][0];
String name = json['name']['first'] + " " + json['name']['last'];
String image = json['picture']['large'];
return User(name, image);
}
}