class MyCrashTestApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('APM异常捕获测试')),body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: [// 1. 同步异常测试ElevatedButton(child: const Text('触发同步异常'),onPressed: () => _throwSyncException(),),const SizedBox(height: 20),// 2. 异步异常测试ElevatedButton(child: const Text('触发异步异常'),onPressed: () => _throwAsyncException(),),const SizedBox(height: 20),// 3. Widget构建异常ElevatedButton(child: const Text('触发Widget异常'),onPressed: () => Navigator.push(context,MaterialPageRoute(builder: (_) => FaultyWidget())),),],),),),);}// 同步异常示例void _throwSyncException() {// 模拟业务逻辑错误final list = [];print(list[0]); // 越界访问}// 异步异常示例Future<void> _throwAsyncException() async {await Future.delayed(Duration(milliseconds: 500));// 模拟异步错误dynamic nullObject = null;print(nullObject.length); // NoSuchMethodError}}// 会抛出异常的Widgetclass FaultyWidget extends StatelessWidget {@overrideWidget build(BuildContext context) {// 故意构造一个会抛出异常的build方法if (DateTime.now().millisecond % 2 == 0) {return Container(color: Colors.blue);}throw Exception('Widget构建时随机异常');}}


文档反馈