-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathauth_flow_builder.dart
More file actions
313 lines (267 loc) · 9.04 KB
/
auth_flow_builder.dart
File metadata and controls
313 lines (267 loc) · 9.04 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright 2022, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:firebase_ui_auth/firebase_ui_auth.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart' as fba;
import 'package:firebase_ui_oauth/firebase_ui_oauth.dart';
import '../auth_controller.dart';
import '../auth_state.dart';
/// {@template ui.auth.widgets.auth_flow_builder.auth_flow_builder_callback}
/// A callback that is being called every time the [AuthFlow] changes it's
/// state. Returned widget is rendered as a child of [AuthFlowBuilder].
/// {@endtemplate}
typedef AuthFlowBuilderCallback<T extends AuthController> = Widget Function(
BuildContext context,
/// Current [AuthState] of the [AuthFlow].
AuthState state,
/// An instance of [AuthController] that could be used to control the
/// [AuthFlow].
T ctrl,
/// A [Widget] that was provided to the [AuthFlowBuilder].
Widget? child,
);
/// {@template ui.auth.widgets.auth_flow_builder.state_transition_listener}
/// A callback that is being called when [AuthFlow] changes it's state.
///
/// Invoked before the widget is built.
/// {@endtemplate}
typedef StateTransitionListener<T extends AuthController> = void Function(
/// Previous state of the [AuthFlow].
AuthState oldState,
/// Current state of the [AuthFlow].
AuthState newState,
/// An instance of the [AuthController] that could be used to manipulate the
/// [AuthFlow].
T controller,
);
/// {@template ui.auth.widgets.auth_flow_builder}
/// A widget that is used to wire up the [AuthFlow]s with the widget tree.
///
/// Could be used to build a custom UI and facilitate the built-in functionality
/// of the all available [AuthFlow]s:
///
/// * [EmailAuthFlow]
/// * [EmailLinkFlow]
/// * [OAuthFlow]
/// * [PhoneAuthFlow]
///
/// An example of how to build a custom email sign up form using
/// [AuthFlowBuilder]:
///
/// ```dart
/// final emailCtrl = TextEditingController();
/// final passwordCtrl = TextEditingController();
///
/// AuthFlowBuilder<EmailAuthController>(
/// auth: fba.FirebaseAuth.instance,
/// action: AuthAction.signUp,
/// listener: (oldState, newState, ctrl) {
/// if (newState is UserCreated) {
/// Navigator.of(context).pushReplacementNamed('/profile');
/// }
/// },
/// builder: (context, state, ctrl, child) {
/// if (state is AwaitingEmailAndPassword) {
/// return Column(
/// children: [
/// TextField(
/// decoration: InputDecoration(labelText: 'Email'),
/// controller: emailCtrl,
/// ),
/// TextField(
/// decoration: InputDecoration(labelText: 'Password'),
/// controller: passwordCtrl,
/// ),
/// OutlinedButton(
/// child: Text('Sign Up'),
/// onPressed: () {
/// ctrl.setEmailAndPassword(emailCtrl.text, passwordCtrl.text);
/// }
/// ),
/// ]
/// );
/// } else if (state is SigningIn) {
/// return Center(child: CircularProgressIndicator());
/// } else if (state is AuthFailed) {
/// return ErrorText(exception: state.exception);
/// }
/// }
/// )
/// ```
/// {@endtemplate}
class AuthFlowBuilder<T extends AuthController> extends StatefulWidget {
static final _flows = <Object, AuthFlow>{};
/// Resolves an [AuthController] by the [flowKey].
static T? getController<T extends AuthController>(Object flowKey) {
final flow = _flows[flowKey];
if (flow == null) return null;
return flow as T;
}
/// Returns a current [AuthState] of the [AuthFlow] given the [flowKey].
static AuthState? getState(Object flowKey) {
final flow = _flows[flowKey];
if (flow == null) return null;
return flow.value;
}
/// A unique object that is used as a key for an [AuthFlow].
/// Could be used to obtain a controller via [getController] or
/// to read a current state using [getState].
final Object? flowKey;
/// {@macro ui.auth.auth_controller.auth}
final fba.FirebaseAuth? auth;
/// {@macro ui.auth.auth_action}
final AuthAction? action;
/// An optional instance of the [AuthProvider] that should be used to
/// authenticate. If not provided, a default instance of the [AuthProvider]
/// will be created. A type of provider is resolved by the type of the
/// [AuthController] provided to the [AuthFlowBuilder].
///
/// The following providers are optional to provide:
/// * [EmailAuthController]
/// * [PhoneAuthController]
final AuthProvider? provider;
/// An optional instance of the [AuthFlow].
/// Should be rarely provided, as the [AuthFlow] is created automatically,
/// based on [provider].
final AuthFlow? flow;
/// {@macro ui.auth.widgets.auth_flow_builder.auth_flow_builder_callback}
final AuthFlowBuilderCallback<T>? builder;
/// A pre-built child that will be provided as an argument of the [builder].
final Widget? child;
/// A callback that is being called when the auth flow completes.
final Function(fba.AuthCredential credential)? onComplete;
/// {@macro ui.auth.widgets.auth_flow_builder.state_transition_listener}
final StateTransitionListener<T>? listener;
/// {@macro ui.auth.widgets.auth_flow_builder}
const AuthFlowBuilder({
super.key,
this.flowKey,
this.action,
this.builder,
this.onComplete,
this.child,
this.listener,
this.provider,
this.auth,
this.flow,
}) : assert(
builder != null || child != null,
'Either child or builder should be provided',
);
@override
// ignore: library_private_types_in_public_api
_AuthFlowBuilderState createState() => _AuthFlowBuilderState<T>();
}
class _AuthFlowBuilderState<T extends AuthController>
extends State<AuthFlowBuilder> {
@override
AuthFlowBuilder<T> get widget => super.widget as AuthFlowBuilder<T>;
AuthFlowBuilderCallback<T> get builder => widget.builder ?? _defaultBuilder;
AuthState? prevState;
late AuthFlow flow;
late AuthAction action;
bool initialized = false;
late AuthProvider provider = widget.provider ?? _createDefaultProvider();
Widget _defaultBuilder(BuildContext _, AuthState __, T ___, Widget? ____) {
return widget.child!;
}
@override
void initState() {
super.initState();
provider.auth = widget.auth ?? fba.FirebaseAuth.instance;
flow = widget.flow ?? createFlow();
if (widget.flowKey != null) {
AuthFlowBuilder._flows[widget.flowKey!] = flow;
flow.onDispose = () {
AuthFlowBuilder._flows.remove(widget.flowKey);
};
}
action = widget.action ??
(flow.auth.currentUser != null ? AuthAction.link : AuthAction.signIn);
flow.addListener(onFlowStateChanged);
prevState = flow.value;
initialized = true;
}
AuthProvider _createDefaultProvider() {
if (T == EmailAuthController) {
return EmailAuthProvider();
} else if (T == PhoneAuthController) {
return PhoneAuthProvider();
} else {
throw Exception("Can't create $T provider");
}
}
AuthFlow createFlow() {
if (widget.flowKey != null) {
final existingFlow = AuthFlowBuilder._flows[widget.flowKey!];
if (existingFlow != null) {
return existingFlow;
}
}
final provider = this.provider;
if (provider is EmailAuthProvider) {
return EmailAuthFlow(
provider: provider,
action: widget.action,
auth: widget.auth,
);
} else if (provider is EmailLinkAuthProvider) {
return EmailLinkFlow(
provider: provider,
auth: widget.auth,
);
} else if (provider is OAuthProvider) {
return OAuthFlow(
provider: provider,
action: widget.action,
auth: widget.auth,
);
} else if (provider is PhoneAuthProvider) {
return PhoneAuthFlow(
provider: provider,
action: widget.action,
auth: widget.auth,
);
} else {
throw Exception('Unknown provider $provider');
}
}
void onFlowStateChanged() {
AuthStateTransition(prevState!, flow.value, flow as T).dispatch(context);
widget.listener?.call(prevState!, flow.value, flow as T);
prevState = flow.value;
}
@override
void didUpdateWidget(covariant AuthFlowBuilder<AuthController> oldWidget) {
flow.action = widget.action ?? action;
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return AuthControllerProvider(
action: flow.action,
ctrl: flow,
child: ValueListenableBuilder<AuthState>(
valueListenable: flow,
builder: (context, value, _) {
final child = builder(
context,
value,
flow as T,
widget.child,
);
return AuthStateProvider(state: value, child: child);
},
),
);
}
@override
void dispose() {
flow.removeListener(onFlowStateChanged);
if (widget.flowKey == null && widget.flow == null) {
flow.reset();
}
super.dispose();
}
}