-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprofile_tab.dart
More file actions
501 lines (454 loc) · 14.7 KB
/
Copy pathprofile_tab.dart
File metadata and controls
501 lines (454 loc) · 14.7 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:klaviyo_flutter_sdk/klaviyo_flutter_sdk.dart';
import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import '../main.dart' show setupSilentPushListener, setupPushActionListener;
import 'forms_tab.dart';
import 'geofencing_tab.dart';
final _logger = Logger('KlaviyoExample');
class ProfileTab extends StatefulWidget {
const ProfileTab({super.key});
@override
State<ProfileTab> createState() => _ProfileTabState();
}
class _ProfileTabState extends State<ProfileTab> {
final KlaviyoSDK _klaviyo = KlaviyoSDK();
final TextEditingController _apiKeyController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _phoneController = TextEditingController();
final TextEditingController _externalIdController = TextEditingController();
final TextEditingController _firstNameController = TextEditingController();
final TextEditingController _lastNameController = TextEditingController();
bool _isInitialized = false;
String _status = 'Enter your Klaviyo API key to initialize';
String? _currentEmail;
String? _currentPhoneNumber;
String? _currentExternalId;
static const String _apiKeyPrefsKey = 'klaviyo_api_key';
//#region Lifecycle
@override
void initState() {
super.initState();
_loadSavedApiKey();
}
Future<void> _loadSavedApiKey() async {
try {
final prefs = await SharedPreferences.getInstance();
final savedApiKey = prefs.getString(_apiKeyPrefsKey);
if (savedApiKey != null && savedApiKey.isNotEmpty) {
setState(() {
_apiKeyController.text = savedApiKey;
});
// Only initialize if not already initialized
if (!_klaviyo.isInitialized) {
await _initializeSDK();
} else {
setState(() {
_isInitialized = true;
_status = 'SDK already initialized';
});
}
}
} catch (e) {
_logger.warning('Failed to load saved API key: $e');
}
}
//#endregion
//#region Business Logic
Future<void> _initializeSDK() async {
final apiKey = _apiKeyController.text.trim();
if (apiKey.isEmpty) {
setState(() {
_status = 'Please enter an API key';
});
return;
}
try {
await _klaviyo.initialize(apiKey: apiKey);
// Save API key
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_apiKeyPrefsKey, apiKey);
// Register FCM token with Klaviyo (Android only)
if (Platform.isAndroid) {
try {
final messaging = FirebaseMessaging.instance;
final token = await messaging.getToken();
if (token != null) {
await _klaviyo.setPushToken(token);
}
} catch (e) {
_logger.warning('Failed to register FCM token: $e');
}
}
// Set up silent push listener now that SDK is initialized
setupSilentPushListener();
// Set up push action (open_url / action button) listener
setupPushActionListener();
// Sync current profile values
await _syncCurrentProfile();
setState(() {
_isInitialized = true;
_status = 'SDK initialized successfully!';
});
} catch (e) {
setState(() {
_status = 'Failed to initialize: $e';
});
}
}
Future<void> _syncCurrentProfile() async {
try {
final email = await _klaviyo.getEmail();
final phoneNumber = await _klaviyo.getPhoneNumber();
final externalId = await _klaviyo.getExternalId();
setState(() {
_currentEmail = email;
_currentPhoneNumber = phoneNumber;
_currentExternalId = externalId;
});
} catch (e) {
setState(() {
_status = 'Failed to sync profile: $e';
});
}
}
Future<void> _setEmail() async {
if (!_isInitialized) return;
try {
await _klaviyo.setEmail(_emailController.text);
await _syncCurrentProfile();
setState(() {
_status = 'Email set successfully';
});
} catch (e) {
setState(() {
_status = 'Failed to set email: $e';
});
}
}
Future<void> _setPhoneNumber() async {
if (!_isInitialized) return;
try {
await _klaviyo.setPhoneNumber(_phoneController.text);
await _syncCurrentProfile();
setState(() {
_status = 'Phone number set successfully';
});
} catch (e) {
setState(() {
_status = 'Failed to set phone number: $e';
});
}
}
Future<void> _setExternalId() async {
if (!_isInitialized) return;
try {
await _klaviyo.setExternalId(_externalIdController.text);
await _syncCurrentProfile();
setState(() {
_status = 'External ID set successfully';
});
} catch (e) {
setState(() {
_status = 'Failed to set external ID: $e';
});
}
}
Future<void> _setFullProfile() async {
if (!_isInitialized) return;
try {
await _klaviyo.setProfile(
KlaviyoProfile(
email:
_emailController.text.isNotEmpty ? _emailController.text : null,
phoneNumber:
_phoneController.text.isNotEmpty ? _phoneController.text : null,
externalId: _externalIdController.text.isNotEmpty
? _externalIdController.text
: null,
firstName: _firstNameController.text.isNotEmpty
? _firstNameController.text
: null,
lastName: _lastNameController.text.isNotEmpty
? _lastNameController.text
: null,
),
);
await _syncCurrentProfile();
setState(() {
_status = 'Full profile set successfully';
});
} catch (e) {
setState(() {
_status = 'Failed to set profile: $e';
});
}
}
Future<void> _resetProfile() async {
if (!_isInitialized) return;
try {
await _klaviyo.resetProfile();
await _syncCurrentProfile();
setState(() {
_emailController.clear();
_phoneController.clear();
_externalIdController.clear();
_firstNameController.clear();
_lastNameController.clear();
_status = 'Profile reset successfully';
});
} catch (e) {
setState(() {
_status = 'Failed to reset profile: $e';
});
}
}
Future<void> _resetSDK() async {
try {
// Reset profile first if initialized
if (_isInitialized) {
await _klaviyo.resetProfile();
}
// Clear saved API key
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_apiKeyPrefsKey);
// Clear all controllers
_apiKeyController.clear();
_emailController.clear();
_phoneController.clear();
_externalIdController.clear();
_firstNameController.clear();
_lastNameController.clear();
// Reset static state in other tabs
FormsTab.resetState();
GeofencingTab.resetState();
setState(() {
_isInitialized = false;
_currentEmail = null;
_currentPhoneNumber = null;
_currentExternalId = null;
_status = 'SDK reset. Enter API key to initialize';
});
} catch (e) {
setState(() {
_status = 'Failed to reset SDK: $e';
});
}
}
//#endregion
//#region View
Widget _buildProfileValueRow(String label, String? value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
'$label:',
style: const TextStyle(
fontWeight: FontWeight.w500,
),
),
),
Expanded(
child: Text(
value ?? '(not set)',
style: TextStyle(
color: value != null ? Colors.black : Colors.grey.shade600,
fontStyle: value != null ? FontStyle.normal : FontStyle.italic,
),
),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Profile'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Status
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _isInitialized
? Colors.green.shade100
: Colors.orange.shade100,
borderRadius: BorderRadius.circular(8),
),
child: Text(
_status,
style: TextStyle(
color: _isInitialized
? Colors.green.shade900
: Colors.orange.shade900,
),
),
),
const SizedBox(height: 20),
// Current Profile Values Section
if (_isInitialized) ...[
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.blue.shade200),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Current Profile Values',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.blue.shade900,
),
),
IconButton(
icon: const Icon(Icons.refresh, size: 20),
onPressed: _syncCurrentProfile,
tooltip: 'Refresh',
),
],
),
const Divider(),
_buildProfileValueRow('Email', _currentEmail),
_buildProfileValueRow('Phone Number', _currentPhoneNumber),
_buildProfileValueRow('External ID', _currentExternalId),
],
),
),
const SizedBox(height: 20),
],
// API Key Section
if (!_isInitialized) ...[
TextField(
controller: _apiKeyController,
decoration: const InputDecoration(
labelText: 'API Key',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _initializeSDK,
child: const Text('Initialize SDK'),
),
],
// Profile Fields (only show when initialized)
if (_isInitialized) ...[
TextField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.emailAddress,
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _setEmail,
child: const Text('Set Email'),
),
const SizedBox(height: 20),
TextField(
controller: _phoneController,
decoration: const InputDecoration(
labelText: 'Phone Number',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.phone,
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _setPhoneNumber,
child: const Text('Set Phone Number'),
),
const SizedBox(height: 20),
TextField(
controller: _externalIdController,
decoration: const InputDecoration(
labelText: 'External ID',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _setExternalId,
child: const Text('Set External ID'),
),
const SizedBox(height: 20),
TextField(
controller: _firstNameController,
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 10),
TextField(
controller: _lastNameController,
decoration: const InputDecoration(
labelText: 'Last Name',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _setFullProfile,
child: const Text('Set Full Profile'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _resetProfile,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
child: const Text('Reset Profile'),
),
const SizedBox(height: 20),
const Divider(),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _resetSDK,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey.shade700,
foregroundColor: Colors.white,
),
child: const Text('Reset SDK & Change API Key'),
),
],
],
),
),
);
}
//#endregion
@override
void dispose() {
_apiKeyController.dispose();
_emailController.dispose();
_phoneController.dispose();
_externalIdController.dispose();
_firstNameController.dispose();
_lastNameController.dispose();
super.dispose();
}
}