This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
main.dart
183 lines (164 loc) · 4.96 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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, avoid_print
import 'dart:async';
import 'dart:convert' show json;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(
const MaterialApp(
title: 'Google Sign In',
home: SignInDemo(),
),
);
}
class SignInDemo extends StatefulWidget {
const SignInDemo({Key? key}) : super(key: key);
@override
State createState() => SignInDemoState();
}
class SignInDemoState extends State<SignInDemo> {
GoogleSignInUserData? _currentUser;
String _contactText = '';
// Future that completes when `init` has completed on the sign in instance.
Future<void>? _initialization;
@override
void initState() {
super.initState();
_signIn();
}
Future<void> _ensureInitialized() {
return _initialization ??=
GoogleSignInPlatform.instance.initWithParams(const SignInInitParameters(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
))
..catchError((dynamic _) {
_initialization = null;
});
}
void _setUser(GoogleSignInUserData? user) {
setState(() {
_currentUser = user;
if (user != null) {
_handleGetContact(user);
}
});
}
Future<void> _signIn() async {
await _ensureInitialized();
final GoogleSignInUserData? newUser =
await GoogleSignInPlatform.instance.signInSilently();
_setUser(newUser);
}
Future<Map<String, String>> _getAuthHeaders() async {
final GoogleSignInUserData? user = _currentUser;
if (user == null) {
throw StateError('No user signed in');
}
final GoogleSignInTokenData response =
await GoogleSignInPlatform.instance.getTokens(
email: user.email,
shouldRecoverAuth: true,
);
return <String, String>{
'Authorization': 'Bearer ${response.accessToken}',
// TODO(kevmoo): Use the correct value once it's available.
// See https://github.com/flutter/flutter/issues/80905
'X-Goog-AuthUser': '0',
};
}
Future<void> _handleGetContact(GoogleSignInUserData user) async {
setState(() {
_contactText = 'Loading contact info...';
});
final http.Response response = await http.get(
Uri.parse('https://people.googleapis.com/v1/people/me/connections'
'?requestMask.includeField=person.names'),
headers: await _getAuthHeaders(),
);
if (response.statusCode != 200) {
setState(() {
_contactText = 'People API gave a ${response.statusCode} '
'response. Check logs for details.';
});
print('People API ${response.statusCode} response: ${response.body}');
return;
}
final Map<String, dynamic> data =
json.decode(response.body) as Map<String, dynamic>;
final int contactCount =
(data['connections'] as List<dynamic>?)?.length ?? 0;
setState(() {
_contactText = '$contactCount contacts found';
});
}
Future<void> _handleSignIn() async {
try {
await _ensureInitialized();
_setUser(await GoogleSignInPlatform.instance.signIn());
} catch (error) {
final bool canceled =
error is PlatformException && error.code == 'sign_in_canceled';
if (!canceled) {
print(error);
}
}
}
Future<void> _handleSignOut() async {
await _ensureInitialized();
await GoogleSignInPlatform.instance.disconnect();
}
Widget _buildBody() {
final GoogleSignInUserData? user = _currentUser;
if (user != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
title: Text(user.displayName ?? ''),
subtitle: Text(user.email),
),
const Text('Signed in successfully.'),
Text(_contactText),
ElevatedButton(
onPressed: _handleSignOut,
child: const Text('SIGN OUT'),
),
ElevatedButton(
child: const Text('REFRESH'),
onPressed: () => _handleGetContact(user),
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text('You are not currently signed in.'),
ElevatedButton(
onPressed: _handleSignIn,
child: const Text('SIGN IN'),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}