-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathmain.dart
More file actions
637 lines (606 loc) · 21.9 KB
/
main.dart
File metadata and controls
637 lines (606 loc) · 21.9 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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
import 'package:posthog_flutter_example/error_example.dart';
Future<void> main() async {
final config =
PostHogConfig('phc_6lqCaCDCBEWdIGieihq5R2dZpPVbAUFISA75vFZow06');
config.onFeatureFlags = () {
debugPrint('[PostHog] Feature flags loaded!');
};
// Configure beforeSend callbacks to filter/modify events
config.beforeSend = [
(event) {
debugPrint('[beforeSend] Event: ${event.event}');
// Test case 1: Drop specific events
if (event.event == 'drop me') {
debugPrint('[beforeSend] Dropping event: ${event.event}');
return null;
}
// Test case 2: Modify event properties
if (event.event == 'modify me') {
event.properties ??= {};
event.properties?['modified_by_before_send'] = true;
debugPrint('[beforeSend] Modified event: ${event.event}');
}
// Pass through all other events unchanged
return event;
},
];
config.debug = true;
config.captureApplicationLifecycleEvents = false;
config.host = 'https://us.i.posthog.com';
config.surveys = false;
config.sessionReplay = false;
config.sessionReplayConfig.maskAllTexts = false;
config.sessionReplayConfig.maskAllImages = false;
config.sessionReplayConfig.throttleDelay = const Duration(milliseconds: 1000);
config.flushAt = 1;
// Configure error tracking and exception capture
config.errorTrackingConfig.captureFlutterErrors =
true; // Capture Flutter framework errors
config.errorTrackingConfig.capturePlatformDispatcherErrors =
true; // Capture Dart runtime errors
config.errorTrackingConfig.captureIsolateErrors =
true; // Capture isolate errors
if (kIsWeb) {
runZonedGuarded(
() async => await _initAndRun(config),
(error, stackTrace) async => await Posthog()
.captureRunZonedGuardedError(error: error, stackTrace: stackTrace),
);
} else {
await _initAndRun(config);
}
}
Future<void> _initAndRun(PostHogConfig config) async {
WidgetsFlutterBinding.ensureInitialized();
await Posthog().setup(config);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return PostHogWidget(
child: MaterialApp(
navigatorObservers: [PosthogObserver()],
title: 'Flutter App',
home: const InitialScreen(),
),
);
}
}
class InitialScreen extends StatefulWidget {
const InitialScreen({Key? key}) : super(key: key);
@override
InitialScreenState createState() => InitialScreenState();
}
class InitialScreenState extends State<InitialScreen> {
final _posthogFlutterPlugin = Posthog();
dynamic _result = "";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('PostHog Flutter App'),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SecondRoute(),
settings: const RouteSettings(name: 'second_route')),
);
},
child: const PostHogMaskWidget(
child: Text(
'Go to Second Route',
),
),
),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Capture",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
_posthogFlutterPlugin
.screen(screenName: "my screen", properties: {
"foo": "bar",
});
},
child: const Text("Capture Screen manually"),
),
ElevatedButton(
onPressed: () {
_posthogFlutterPlugin
.capture(eventName: "eventName", properties: {
"foo": "bar",
}, userProperties: {
"user_foo": "user_bar",
}, userPropertiesSetOnce: {
"user_foo_once": "user_bar_once",
});
},
child: const Text("Capture Event"),
),
],
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Activity",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Wrap(
alignment: WrapAlignment.spaceEvenly,
spacing: 8.0,
runSpacing: 8.0,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
_posthogFlutterPlugin.disable();
},
child: const Text("Disable Capture"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
),
onPressed: () {
_posthogFlutterPlugin.enable();
},
child: const Text("Enable Capture"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
),
onPressed: () async {
final isOptedOut =
await _posthogFlutterPlugin.isOptOut();
if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Opted out: $isOptedOut'),
duration: const Duration(seconds: 2),
),
);
}
},
child: const Text("Check Opt-Out Status"),
),
],
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.register("foo", "bar");
},
child: const Text("Register"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.unregister("foo");
},
child: const Text("Unregister"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.group(
groupType: "theType",
groupKey: "theKey",
groupProperties: {
"foo": "bar",
});
},
child: const Text("Group"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin
.identify(userId: "myId", userProperties: {
"foo": "bar",
}, userPropertiesSetOnce: {
"foo1": "bar1",
});
},
child: const Text("Identify"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.alias(alias: "myAlias");
},
child: const Text("Alias"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.debug(true);
},
child: const Text("Debug"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.reset();
},
child: const Text("Reset"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.flush();
},
child: const Text("Flush"),
),
ElevatedButton(
onPressed: () async {
final result =
await _posthogFlutterPlugin.getDistinctId();
setState(() {
_result = result;
});
},
child: const PostHogMaskWidget(
child: Text("distinctId"),
)),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Error Tracking - Manual",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
ElevatedButton(
onPressed: () async {
await ErrorExample().causeHandledDivisionError();
},
child: const Text("Capture Exception"),
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Error Tracking - Autocapture",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () async {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content:
Text('Flutter error triggered! Check PostHog.'),
backgroundColor: Colors.red,
duration: Duration(seconds: 3),
),
);
}
// Test Flutter error handler by throwing in widget context
await ErrorExample().causeHandledDivisionError();
},
child: const Text("Test Flutter Error Handler"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
onPressed: () async {
await ErrorExample().throwWithinDelayed();
if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Dart runtime error triggered! Check PostHog.'),
backgroundColor: Colors.blue,
duration: Duration(seconds: 3),
),
);
}
},
child: const Text("Test Dart Error Handler"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
foregroundColor: Colors.white,
),
onPressed: () async {
// Test isolate error listener by throwing in an async callback
await ErrorExample().throwWithinTimer();
if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content:
Text('Isolate error triggered! Check PostHog.'),
backgroundColor: Colors.purple,
duration: Duration(seconds: 3),
),
);
}
},
child: const Text("Test Isolate Error Handler"),
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"beforeSend Tests",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Wrap(
alignment: WrapAlignment.spaceEvenly,
spacing: 8.0,
runSpacing: 8.0,
children: [
ElevatedButton(
onPressed: () {
_posthogFlutterPlugin.capture(
eventName: 'normal_event',
properties: {'test': 'pass_through'},
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Normal event sent (should appear in PostHog)'),
duration: Duration(seconds: 2),
),
);
},
child: const Text("Normal Event"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () {
_posthogFlutterPlugin.capture(
eventName: 'drop me',
properties: {'should_be': 'dropped'},
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Drop event sent (should NOT appear in PostHog)'),
backgroundColor: Colors.red,
duration: Duration(seconds: 2),
),
);
},
child: const Text("Drop Event"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
foregroundColor: Colors.white,
),
onPressed: () {
_posthogFlutterPlugin.capture(
eventName: 'modify me',
properties: {'original': true},
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Modify event sent (check for modified_by_before_send property)'),
backgroundColor: Colors.orange,
duration: Duration(seconds: 2),
),
);
},
child: const Text("Modify Event"),
),
],
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Feature flags",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
ElevatedButton(
onPressed: () async {
final result = await _posthogFlutterPlugin
.getFeatureFlag("feature_name");
setState(() {
_result = result;
});
},
child: const Text("Get Feature Flag status"),
),
ElevatedButton(
onPressed: () async {
final result = await _posthogFlutterPlugin
.isFeatureEnabled("feature_name");
setState(() {
_result = result;
});
},
child: const Text("isFeatureEnabled"),
),
ElevatedButton(
onPressed: () async {
final result = await _posthogFlutterPlugin
.getFeatureFlagPayload("feature_name");
setState(() {
_result = result;
});
},
child: const Text("getFeatureFlagPayload"),
),
ElevatedButton(
onPressed: () async {
final result = await _posthogFlutterPlugin
.getFeatureFlagResult("feature_name");
setState(() {
_result = result?.toString();
});
},
child: const Text("getFeatureFlagResult"),
),
ElevatedButton(
onPressed: () async {
await _posthogFlutterPlugin.reloadFeatureFlags();
},
child: const PostHogMaskWidget(
child: Text("reloadFeatureFlags")),
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Data result",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Text(_result.toString()),
],
),
),
),
),
);
}
}
class SecondRoute extends StatefulWidget {
const SecondRoute({super.key});
@override
SecondRouteState createState() => SecondRouteState();
}
class SecondRouteState extends State<SecondRoute> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const PostHogMaskWidget(child: Text('First Route')),
),
body: Center(
child: RepaintBoundary(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const PostHogMaskWidget(child: Text('Open route')),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ThirdRoute(),
settings: const RouteSettings(name: 'third_route'),
),
).then((_) {});
},
),
const SizedBox(height: 20),
const TextField(
decoration: InputDecoration(
labelText: 'Sensitive Text Input',
hintText: 'Enter sensitive data',
border: OutlineInputBorder(),
),
obscureText: true,
),
const SizedBox(height: 20),
PostHogMaskWidget(
child: Image.asset(
'assets/training_posthog.png',
height: 200,
)),
const SizedBox(height: 20),
],
),
),
),
);
}
}
class ThirdRoute extends StatelessWidget {
const ThirdRoute({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Third Route'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
),
itemCount: 16,
itemBuilder: (context, index) {
return Image.asset(
'assets/posthog_logo.png',
fit: BoxFit.cover,
);
},
),
),
);
}
}
/// Custom exception class for demonstration purposes
class CustomException implements Exception {
final String message;
final String? code;
final Map<String, dynamic>? additionalData;
const CustomException(
this.message, {
this.code,
this.additionalData,
});
@override
String toString() {
if (code != null) {
return 'CustomException($code): $message $additionalData';
}
return 'CustomException: $message $additionalData';
}
}