-
-
Notifications
You must be signed in to change notification settings - Fork 220
/
main.dart
647 lines (604 loc) · 19.8 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
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
638
639
640
641
642
643
644
645
646
647
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:universal_platform/universal_platform.dart';
import 'package:feedback/feedback.dart' as feedback;
import 'package:provider/provider.dart';
import 'user_feedback_dialog.dart';
import 'package:dio/dio.dart';
import 'package:sentry_dio/sentry_dio.dart';
// ATTENTION: Change the DSN below with your own to see the events in Sentry. Get one at sentry.io
const String _exampleDsn =
'https://9934c532bf8446ef961450973c898537@o447951.ingest.sentry.io/5428562';
final _channel = const MethodChannel('example.flutter.sentry.io');
Future<void> main() async {
await SentryFlutter.init(
(options) {
options.dsn = _exampleDsn;
options.tracesSampleRate = 1.0;
options.reportPackages = false;
options.addInAppInclude('sentry_flutter_example');
options.considerInAppFramesByDefault = false;
options.attachThreads = true;
options.enableWindowMetricBreadcrumbs = true;
},
// Init your App.
appRunner: () => runApp(
DefaultAssetBundle(
bundle: SentryAssetBundle(enableStructuredDataTracing: true),
child: MyApp(),
),
),
);
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return feedback.BetterFeedback(
child: ChangeNotifierProvider<ThemeProvider>(
create: (_) => ThemeProvider(),
child: Builder(
builder: (context) => MaterialApp(
navigatorObservers: [
SentryNavigatorObserver(),
],
theme: Provider.of<ThemeProvider>(context).theme,
home: const MainScaffold(),
),
),
),
);
}
}
class MainScaffold extends StatelessWidget {
const MainScaffold({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeProvider>(context);
var icon = Icons.light_mode;
var theme = ThemeData.light();
if (themeProvider.theme.brightness == Brightness.light) {
icon = Icons.dark_mode;
theme = ThemeData.dark();
}
return Scaffold(
appBar: AppBar(
title: const Text('Sentry Flutter Example'),
actions: [
IconButton(
onPressed: () {
themeProvider.theme = theme;
},
icon: Icon(icon),
),
IconButton(
onPressed: () {
themeProvider.updatePrimatryColor(Colors.orange);
},
icon: Icon(Icons.circle, color: Colors.orange),
),
IconButton(
onPressed: () {
themeProvider.updatePrimatryColor(Colors.green);
},
icon: Icon(Icons.circle, color: Colors.lime),
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
const Center(child: Text('Trigger an action:\n')),
ElevatedButton(
onPressed: () => SecondaryScaffold.openSecondaryScaffold(context),
child: const Text('Open another Scaffold'),
),
ElevatedButton(
onPressed: () => tryCatch(),
child: const Text('Dart: try catch'),
),
ElevatedButton(
onPressed: () => Scaffold.of(context).showBottomSheet<dynamic>(
(context) => const Text('Scaffold error'),
),
child: const Text('Flutter error : Scaffold.of()'),
),
ElevatedButton(
// Warning : not captured if a debugger is attached
// https://github.com/flutter/flutter/issues/48972
onPressed: () => throw Exception('Throws onPressed'),
child: const Text('Dart: throw onPressed'),
),
ElevatedButton(
onPressed: () {
// Only relevant in debug builds
// Warning : not captured if a debugger is attached
// https://github.com/flutter/flutter/issues/48972
assert(false, 'assert failure');
},
child: const Text('Dart: assert'),
),
// Calling the SDK with an appRunner will handle errors from Futures
// in SDKs runZonedGuarded onError handler
ElevatedButton(
onPressed: () async => asyncThrows(),
child: const Text('Dart: async throws'),
),
ElevatedButton(
onPressed: () async => {
await Future.microtask(
() => throw StateError('Failure in a microtask'),
)
},
child: const Text('Dart: Fail in microtask.'),
),
ElevatedButton(
onPressed: () async => {await compute(loop, 10)},
child: const Text('Dart: Fail in compute'),
),
ElevatedButton(
onPressed: () => Future.delayed(
Duration(milliseconds: 100),
() => throw Exception('Throws in Future.delayed'),
),
child: const Text('Throws in Future.delayed'),
),
ElevatedButton(
onPressed: () {
// modeled after a real exception
FlutterError.onError?.call(FlutterErrorDetails(
exception: Exception('A really bad exception'),
silent: false,
context: DiagnosticsNode.message('while handling a gesture'),
library: 'gesture',
informationCollector: () => [
DiagnosticsNode.message(
'Handler: "onTap" Recognizer: TapGestureRecognizer'),
DiagnosticsNode.message(
'Handler: "onTap" Recognizer: TapGestureRecognizer'),
DiagnosticsNode.message(
'Handler: "onTap" Recognizer: TapGestureRecognizer'),
],
));
},
child: const Text('Capture from FlutterError.onError'),
),
ElevatedButton(
onPressed: () => makeWebRequest(context),
child: const Text('Dart: Web request'),
),
ElevatedButton(
onPressed: () => showDialogWithTextAndImage(context),
child: const Text('Flutter: Load assets'),
),
ElevatedButton(
onPressed: () => makeWebRequestWithDio(context),
child: const Text('Dio: Web request'),
),
ElevatedButton(
onPressed: () {
print('A print breadcrumb');
Sentry.captureMessage('A message with a print() Breadcrumb');
},
child: const Text('Record print() as breadcrumb'),
),
ElevatedButton(
onPressed: () {
Sentry.captureMessage(
'This event has an extra tag',
withScope: (scope) {
scope.setTag('foo', 'bar');
},
);
},
child:
const Text('Capture message with scope with additional tag'),
),
ElevatedButton(
onPressed: () async {
final transaction = Sentry.getSpan() ??
Sentry.startTransaction(
'myNewTrWithError3',
'myNewOp',
description: 'myTr myOp',
);
transaction.setTag('myTag', 'myValue');
transaction.setData('myExtra', 'myExtraValue');
await Future.delayed(Duration(milliseconds: 50));
final span = transaction.startChild(
'childOfMyOp',
description: 'childOfMyOp span',
);
span.setTag('myNewTag', 'myNewValue');
span.setData('myNewData', 'myNewDataValue');
await Future.delayed(Duration(milliseconds: 70));
await span.finish(status: SpanStatus.resourceExhausted());
await Future.delayed(Duration(milliseconds: 90));
final spanChild = span.startChild(
'childOfChildOfMyOp',
description: 'childOfChildOfMyOp span',
);
await Future.delayed(Duration(milliseconds: 110));
spanChild.startChild(
'unfinishedChild',
description: 'I wont finish',
);
await spanChild.finish(status: SpanStatus.internalError());
await Future.delayed(Duration(milliseconds: 50));
await transaction.finish(status: SpanStatus.ok());
},
child: const Text('Capture transaction'),
),
ElevatedButton(
onPressed: () {
Sentry.captureMessage(
'This message has an attachment',
withScope: (scope) {
final txt = 'Lorem Ipsum dolar sit amet';
scope.addAttachment(
SentryAttachment.fromIntList(
utf8.encode(txt),
'foobar.txt',
contentType: 'text/plain',
),
);
},
);
},
child: const Text('Capture message with attachment'),
),
ElevatedButton(
onPressed: () {
feedback.BetterFeedback.of(context)
.show((feedback.UserFeedback feedback) {
Sentry.captureMessage(
feedback.text,
withScope: (scope) {
final entries = feedback.extra?.entries;
if (entries != null) {
for (final extra in entries) {
scope.setExtra(extra.key, extra.value);
}
}
scope.addAttachment(
SentryAttachment.fromUint8List(
feedback.screenshot,
'feedback.png',
contentType: 'image/png',
),
);
},
);
});
},
child: const Text('Capture message with image attachment'),
),
ElevatedButton(
onPressed: () async {
final id = await Sentry.captureMessage('UserFeedback');
await showDialog(
context: context,
builder: (context) {
return UserFeedbackDialog(eventId: id);
},
);
},
child: const Text('Capture User Feedback'),
),
ElevatedButton(
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return UserFeedbackDialog(eventId: SentryId.newId());
},
);
},
child: const Text('Show UserFeedback Dialog without event'),
),
if (UniversalPlatform.isIOS || UniversalPlatform.isMacOS)
const CocoaExample(),
if (UniversalPlatform.isAndroid) const AndroidExample(),
],
),
),
);
}
}
class AndroidExample extends StatelessWidget {
const AndroidExample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(children: [
ElevatedButton(
onPressed: () async {
await execute('throw');
},
child: const Text('Kotlin Throw unhandled exception'),
),
ElevatedButton(
onPressed: () async {
await execute('capture');
},
child: const Text('Kotlin Capture Exception'),
),
ElevatedButton(
// ANR is disabled by default, enable it to test it
onPressed: () async {
await execute('anr');
},
child: const Text('ANR: UI blocked 6 seconds'),
),
ElevatedButton(
onPressed: () async {
await execute('cpp_capture_message');
},
child: const Text('C++ Capture message'),
),
ElevatedButton(
onPressed: () async {
await execute('crash');
},
child: const Text('C++ SEGFAULT'),
),
ElevatedButton(
onPressed: () async {
await execute('platform_exception');
},
child: const Text('Platform exception'),
),
]);
}
}
Future<void> tryCatch() async {
try {
throw StateError('try catch');
} catch (error, stackTrace) {
await Sentry.captureException(error, stackTrace: stackTrace);
}
}
Future<void> asyncThrows() async {
throw StateError('async throws');
}
class CocoaExample extends StatelessWidget {
const CocoaExample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(
onPressed: () async {
await execute('fatalError');
},
child: const Text('Swift fatalError'),
),
ElevatedButton(
onPressed: () async {
await execute('capture');
},
child: const Text('Swift Capture NSException'),
),
ElevatedButton(
onPressed: () async {
await execute('capture_message');
},
child: const Text('Swift Capture message'),
),
ElevatedButton(
onPressed: () async {
await execute('throw');
},
child: const Text('Objective-C Throw unhandled exception'),
),
ElevatedButton(
onPressed: () async {
await execute('crash');
},
child: const Text('Objective-C SEGFAULT'),
),
],
);
}
}
/// compute can only take a top-level function, but not instance or static methods.
// Top-level functions are functions declared not inside a class and not inside another function
int loop(int val) {
var count = 0;
for (var i = 1; i <= val; i++) {
count += i;
}
throw StateError('from a compute isolate $count');
}
class SecondaryScaffold extends StatelessWidget {
static Future<void> openSecondaryScaffold(BuildContext context) {
return Navigator.push(
context,
MaterialPageRoute<void>(
settings:
const RouteSettings(name: 'SecondaryScaffold', arguments: 'foobar'),
builder: (context) {
return SecondaryScaffold();
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SecondaryScaffold'),
),
body: Center(
child: Column(
children: [
const Text(
'You have added a navigation event '
'to the crash reports breadcrumbs.',
),
MaterialButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Go back'),
),
MaterialButton(
onPressed: () {
throw Exception('Exception from SecondaryScaffold');
},
child: const Text('throw uncaught exception'),
),
],
),
),
);
}
}
Future<void> makeWebRequest(BuildContext context) async {
final transaction = Sentry.getSpan() ??
Sentry.startTransaction(
'flutterwebrequest',
'request',
bindToScope: true,
);
final client = SentryHttpClient(
captureFailedRequests: true,
maxRequestBodySize: MaxRequestBodySize.always,
networkTracing: true,
failedRequestStatusCodes: [SentryStatusCode.range(400, 500)],
);
// We don't do any exception handling here.
// In case of an exception, let it get caught and reported to Sentry
final response = await client.get(Uri.parse('https://flutter.dev/'));
await transaction.finish(status: SpanStatus.ok());
await showDialog<void>(
context: context,
// gets tracked if using SentryNavigatorObserver
routeSettings: RouteSettings(
name: 'flutter.dev dialog',
),
builder: (context) {
return AlertDialog(
title: Text('Response ${response.statusCode}'),
content: SingleChildScrollView(
child: Text(response.body),
),
actions: [
MaterialButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
)
],
);
},
);
}
Future<void> makeWebRequestWithDio(BuildContext context) async {
final dio = Dio();
dio.addSentry(
captureFailedRequests: true,
maxRequestBodySize: MaxRequestBodySize.always,
);
final transaction = Sentry.getSpan() ??
Sentry.startTransaction(
'dio-web-request',
'request',
bindToScope: true,
);
Response<String>? response;
try {
response = await dio.get<String>('https://flutter.dev/');
transaction.status = SpanStatus.ok();
} catch (exception, stackTrace) {
transaction.throwable = exception;
transaction.status = SpanStatus.internalError();
await Sentry.captureException(exception, stackTrace: stackTrace);
} finally {
await transaction.finish();
}
await showDialog<void>(
context: context,
// gets tracked if using SentryNavigatorObserver
routeSettings: RouteSettings(
name: 'flutter.dev dialog',
),
builder: (context) {
return AlertDialog(
title: Text('Response ${response?.statusCode}'),
content: SingleChildScrollView(
child: Text(response?.data ?? 'failed request'),
),
actions: [
MaterialButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
)
],
);
},
);
}
Future<void> showDialogWithTextAndImage(BuildContext context) async {
final transaction = Sentry.getSpan() ??
Sentry.startTransaction(
'asset-bundle-transaction',
'load',
bindToScope: true,
);
final text =
await DefaultAssetBundle.of(context).loadString('assets/lorem-ipsum.txt');
await showDialog<void>(
context: context,
// gets tracked if using SentryNavigatorObserver
routeSettings: RouteSettings(
name: 'AssetBundle dialog',
),
builder: (context) {
return AlertDialog(
title: Text('Asset Example'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset('assets/sentry-wordmark.png'),
Text(text),
],
),
),
actions: [
MaterialButton(
onPressed: () => Navigator.pop(context),
child: Text('Close'),
)
],
);
},
);
await transaction.finish(status: SpanStatus.ok());
}
class ThemeProvider extends ChangeNotifier {
ThemeData _theme = ThemeData.light();
ThemeData get theme => _theme;
set theme(ThemeData theme) {
_theme = theme;
notifyListeners();
}
void updatePrimatryColor(MaterialColor color) {
if (theme.brightness == Brightness.light) {
theme = ThemeData(primarySwatch: color, brightness: theme.brightness);
} else {
theme = ThemeData(primarySwatch: color, brightness: theme.brightness);
}
}
}
Future<void> execute(String method) async {
await _channel.invokeMethod<void>(method);
}