-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathphone_input.dart
More file actions
347 lines (312 loc) · 10.3 KB
/
phone_input.dart
File metadata and controls
347 lines (312 loc) · 10.3 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// 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:flutter/cupertino.dart';
import 'package:firebase_ui_localizations/firebase_ui_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../validators.dart';
import '../widgets/internal/universal_text_form_field.dart';
part '../configs/countries.dart';
class _CountryCodeItem {
final String countryCode;
final String phoneCode;
final String name;
_CountryCodeItem({
required this.countryCode,
required this.phoneCode,
required this.name,
});
static _CountryCodeItem fromJson(Map<String, String> data) {
return _CountryCodeItem(
countryCode: data['countryCode']!,
phoneCode: data['phoneCode']!,
name: data['name']!,
);
}
}
typedef SubmitCallback = void Function(String value);
class _CountryPicker extends StatefulWidget {
const _CountryPicker();
@override
_CountryPickerState createState() => _CountryPickerState();
}
class _CountryPickerState extends State<_CountryPicker> {
String? _countryCode;
String get countryCode => _countryCode!;
String get phoneCode => countriesByCountryCode[countryCode]!.phoneCode;
@override
Widget build(BuildContext context) {
_countryCode ??= Localizations.localeOf(context).countryCode;
final item = countriesByCountryCode[_countryCode]!;
return PopupMenuButton<_CountryCodeItem>(
onSelected: (selected) => setState(() {
_countryCode = selected.countryCode;
}),
itemBuilder: (context) {
return countries.map((e) {
return PopupMenuItem(
value: e,
child: Text('${e.name} (+${e.phoneCode})'),
);
}).toList();
},
child: Container(
padding: const EdgeInsets.all(16).copyWith(left: 0),
child: Row(
children: [
const Icon(Icons.arrow_drop_down),
Text(
'${item.countryCode} (+${item.phoneCode})',
style: const TextStyle(fontSize: 16),
),
],
),
),
);
}
}
/// {@template ui.auth.widgets.phone_input}
/// An input that allows to enter a phone number and select a country code.
/// {@endtemplate}
class PhoneInput extends StatefulWidget {
/// A callback that is being called when the input is submitted.
final SubmitCallback? onSubmit;
/// An initial country code that should be selected in the country code
/// picker.
final String? initialCountryCode;
/// Whether the phone input text field should be focused as soon as it's visible.
final bool autoFocus;
/// Returns a phone number from the [PhoneInput] that was provided a [key].
static String? getPhoneNumber(GlobalKey<PhoneInputState> key) {
final state = key.currentState!;
if (state.formKey.currentState!.validate()) {
return state.phoneNumber;
}
return null;
}
/// {@macro ui.auth.widgets.phone_input}
const PhoneInput({
super.key,
this.initialCountryCode,
this.autoFocus = true,
this.onSubmit,
});
@override
PhoneInputState createState() => PhoneInputState();
}
/// A state of the [PhoneInput].
///
/// Shouldn't be used directly.
/// Should be used only to construct a key for phone input.
///
/// ```dart
/// final key = GlobalKey<PhoneInputState>();
/// return PhoneInput(key: key);
/// ```
class PhoneInputState extends State<PhoneInput> {
late final countryController = TextEditingController()
..addListener(_onCountryChanged);
final numberController = TextEditingController();
final formKey = GlobalKey<FormState>();
final numberFocusNode = FocusNode();
String get phoneNumber =>
'+${countryController.text}${numberController.text}';
String? country;
bool isValidCountryCode = true;
// ignore: library_private_types_in_public_api
_CountryCodeItem? countryCodeItem;
void _onSubmitted(void _) {
if (formKey.currentState!.validate()) {
widget.onSubmit?.call(phoneNumber);
}
}
@override
void initState() {
_setCountry(countryCode: widget.initialCountryCode);
super.initState();
}
void _setCountry({
String? phoneCode,
String? countryCode,
bool updateCountryInput = true,
}) {
try {
final newItem = countries.firstWhere(
(element) =>
element.countryCode == countryCode ||
element.phoneCode == phoneCode,
);
if (phoneCode != null &&
newItem.phoneCode == countryCodeItem?.phoneCode) {
return;
}
countryCodeItem = newItem;
isValidCountryCode = true;
} catch (_) {
countryCodeItem = null;
isValidCountryCode = false;
}
if (updateCountryInput) {
countryController.text = countryCodeItem?.phoneCode ?? '';
}
}
void _onCountryChanged() {
setState(() {
_setCountry(
phoneCode: countryController.text,
updateCountryInput: false,
);
});
}
void _showCountryPicker(BuildContext context) {
final l = FirebaseUILocalizations.labelsOf(context);
showCupertinoModalPopup(
context: context,
builder: (context) {
return Container(
color: CupertinoTheme.of(context).scaffoldBackgroundColor,
height: 300,
child: Column(
children: [
Expanded(
child: CupertinoPicker.builder(
useMagnifier: true,
itemExtent: 40,
childCount: countries.length,
onSelectedItemChanged: (i) {
setState(() {
_setCountry(
countryCode: countries.elementAt(i).countryCode,
);
});
},
itemBuilder: (context, index) {
final item = countries.elementAt(index);
return Center(
child: Text(
'${item.name} (+${item.phoneCode})',
style: const TextStyle(fontSize: 16),
),
);
},
),
),
CupertinoButton(
child: Text(l.doneButtonLabel),
onPressed: () => Navigator.pop(context),
),
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
final l = FirebaseUILocalizations.labelsOf(context);
final isCupertino = CupertinoUserInterfaceLevel.maybeOf(context) != null;
return Form(
key: formKey,
child: Column(
children: [
if (isCupertino)
GestureDetector(
onTap: () {
_showCountryPicker(context);
},
child: Row(
children: [
const Icon(Icons.arrow_drop_down),
Text(
countryController.text.isNotEmpty && !isValidCountryCode
? l.invalidCountryCode
: countryCodeItem?.name ?? l.chooseACountry,
),
],
),
)
else
PopupMenuButton<_CountryCodeItem>(
child: Container(
padding: const EdgeInsets.all(16).copyWith(left: 0),
child: Row(
children: [
const Icon(Icons.arrow_drop_down),
Text(
countryController.text.isNotEmpty && !isValidCountryCode
? l.invalidCountryCode
: countryCodeItem?.name ?? l.chooseACountry,
style: const TextStyle(fontSize: 16),
),
],
),
),
itemBuilder: (context) {
return countries.map((e) {
return PopupMenuItem(
value: e,
child: Text('${e.name} (+${e.phoneCode})'),
);
}).toList();
},
onSelected: (selected) => _setCountry(
countryCode: selected.countryCode,
),
),
const SizedBox(height: 16),
Directionality(
textDirection: TextDirection.ltr,
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 90,
child: UniversalTextFormField(
autofillHints: const [
AutofillHints.telephoneNumberCountryCode
],
controller: countryController,
prefix: const Text('+'),
placeholder: l.countryCode,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
keyboardType: TextInputType.phone,
validator: NotEmpty('').validate,
onSubmitted: (_) {
numberFocusNode.requestFocus();
},
),
),
const SizedBox(width: 8),
Expanded(
child: UniversalTextFormField(
autofillHints: const [
AutofillHints.telephoneNumberNational
],
autofocus: widget.autoFocus,
focusNode: numberFocusNode,
controller: numberController,
placeholder: l.phoneInputLabel,
validator: Validator.validateAll([
NotEmpty(l.phoneNumberIsRequiredErrorText),
PhoneValidator(l.phoneNumberInvalidErrorText),
]),
onSubmitted: _onSubmitted,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
keyboardType: TextInputType.phone,
),
),
],
),
),
),
],
),
);
}
}