forked from zino-hofmann/graphql-flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
241 lines (215 loc) · 7.27 KB
/
main.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../graphql_operation/mutations/mutations.dart' as mutations;
import '../graphql_operation/queries/readRepositories.dart' as queries;
const String YOUR_PERSONAL_ACCESS_TOKEN = '<YOUR_PERSONAL_ACCESS_TOKEN>';
const bool ENABLE_WEBSOCKETS = false;
class GraphQLWidgetScreen extends StatelessWidget {
const GraphQLWidgetScreen() : super();
@override
Widget build(BuildContext context) {
final HttpLink httpLink = HttpLink(
uri: 'https://api.github.com/graphql',
);
final AuthLink authLink = AuthLink(
getToken: () async => 'Bearer $YOUR_PERSONAL_ACCESS_TOKEN',
);
// TODO don't think we have to cast here, maybe covariant
Link link = authLink.concat(httpLink as Link);
if (ENABLE_WEBSOCKETS) {
final WebSocketLink websocketLink = WebSocketLink(
url: 'ws://localhost:8080/ws/graphql',
config: SocketClientConfig(
autoReconnect: true, inactivityTimeout: Duration(seconds: 15)),
);
link = link.concat(websocketLink);
}
final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
GraphQLClient(
cache: OptimisticCache(
dataIdFromObject: typenameDataIdFromObject,
),
link: link,
),
);
return GraphQLProvider(
client: client,
child: const CacheProvider(
child: MyHomePage(title: 'GraphQL Widget'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key key,
this.title,
}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int nRepositories = 50;
void changeQuery(String number) {
setState(() {
nRepositories = int.parse(number) ?? 50;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
TextField(
decoration: const InputDecoration(
labelText: 'Number of repositories (default 50)',
),
keyboardType: TextInputType.number,
onSubmitted: changeQuery,
),
Query(
options: QueryOptions(
document: queries.readRepositories,
variables: <String, dynamic>{
'nRepositories': nRepositories,
},
//pollInterval: 10,
),
builder: (QueryResult result, {VoidCallback refetch}) {
if (result.loading) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (result.hasErrors) {
return Text('\nErrors: \n ' + result.errors.join(',\n '));
}
if (result.data == null && result.errors == null) {
return const Text(
'Both data and errors are null, this is a known bug after refactoring, you might forget to set Github token');
}
// result.data can be either a [List<dynamic>] or a [Map<String, dynamic>]
final List<LazyCacheMap> repositories = (result.data['viewer']
['repositories']['nodes'] as List<dynamic>)
.cast<LazyCacheMap>();
return Expanded(
child: ListView.builder(
itemCount: repositories.length,
itemBuilder: (BuildContext context, int index) {
return StarrableRepository(
repository: repositories[index]);
},
),
);
},
),
ENABLE_WEBSOCKETS
? Subscription<Map<String, dynamic>>(
'test', queries.testSubscription, builder: ({
bool loading,
Map<String, dynamic> payload,
dynamic error,
}) {
return loading
? const Text('Loading...')
: Text(payload.toString());
})
: const Text(''),
],
),
),
);
}
}
class StarrableRepository extends StatelessWidget {
const StarrableRepository({
Key key,
@required this.repository,
}) : super(key: key);
final Map<String, Object> repository;
Map<String, Object> extractRepositoryData(Object data) {
final Map<String, Object> action =
(data as Map<String, Object>)['action'] as Map<String, Object>;
if (action == null) {
return null;
}
return action['starrable'] as Map<String, Object>;
}
bool get starred => repository['viewerHasStarred'] as bool;
bool get optimistic => (repository as LazyCacheMap).isOptimistic;
Map<String, dynamic> get expectedResult => <String, dynamic>{
'action': <String, dynamic>{
'starrable': <String, dynamic>{'viewerHasStarred': !starred}
}
};
@override
Widget build(BuildContext context) {
return Mutation(
options: MutationOptions(
document: starred ? mutations.removeStar : mutations.addStar,
),
builder: (RunMutation toggleStar, QueryResult result) {
return ListTile(
leading: starred
? const Icon(
Icons.star,
color: Colors.amber,
)
: const Icon(Icons.star_border),
trailing: result.loading || optimistic
? const CircularProgressIndicator()
: null,
title: Text(repository['name'] as String),
onTap: () {
toggleStar(
<String, dynamic>{
'starrableId': repository['id'],
},
optimisticResult: expectedResult,
);
},
);
},
update: (Cache cache, QueryResult result) {
if (result.hasErrors) {
print(result.errors);
} else {
final Map<String, Object> updated =
Map<String, Object>.from(repository)
..addAll(extractRepositoryData(result.data));
cache.write(typenameDataIdFromObject(updated), updated);
}
},
onCompleted: (dynamic resultData) {
showDialog<AlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
extractRepositoryData(resultData)['viewerHasStarred'] as bool
? 'Thanks for your star!'
: 'Sorry you changed your mind!',
),
actions: <Widget>[
SimpleDialogOption(
child: const Text('DISMISS'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
},
);
}
}