溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Flutter里面錯誤捕獲的正確方法

發(fā)布時間:2021-10-13 11:03:42 來源:億速云 閱讀:89 作者:柒染 欄目:編程語言

本篇文章給大家分享的是有關(guān)Flutter里面錯誤捕獲的正確方法,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

背景

我們知道,在軟件開發(fā)過程中,錯誤和異??偸窃谒y免。

不管是客戶端的邏輯錯誤導(dǎo)致的,還是服務(wù)器的數(shù)據(jù)問題導(dǎo)致的,只要出現(xiàn)了異常,我們都需要一個機制來通知我們?nèi)ヌ幚怼?/p>

在 APP 的開發(fā)過程中,我們通過一些第三方的平臺,比如 Fabric、Bugly 等可以實現(xiàn)異常的日志上報。

Flutter 也有一些第三方的平臺,比如 Sentry 可以實現(xiàn)異常的日志上報。

但是為了更加通用一些,本篇不具體講解配合某個第三方平臺的異常日志捕獲,我們會告知大家如何在 Flutter 里面捕獲異常。

至于具體的上報途徑,不管是上報到自家的后臺服務(wù)器,還是通過第三方的 SDK API 接口進行異常上報,都是可以的。

Demo 初始狀態(tài)

首先我們新建 Flutter 項目,修改 main.dart 代碼如下:

import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) {  return MaterialApp(   home: Scaffold(    appBar: AppBar(title: Text('Flutter Crash Capture'),),    body: MyHomePage(),   ),  ); }}class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) {  return Container(); }}

效果如下:

捕獲錯誤

我們修改 MyHomePage,添加一個 List 然后進行越界訪問,改動部分代碼如下:

class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) {  List<String> numList = ['1', '2'];  print(numList[6]);  return Container(); }}

可以看到控制臺報錯如下:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════flutter: The following RangeError was thrown building MyHomePage(dirty):flutter: RangeError (index): Invalid value: Not in range 0..1, inclusive: 6

當(dāng)然這些錯誤信息在界面上也有顯示(debug 模式)。

那么我們?nèi)绾尾东@呢?

其實很簡單,有個通用模板,模板為:

import 'dart:async';import 'package:flutter/material.dart';Future<Null> main() async { FlutterError.onError = (FlutterErrorDetails details) async {  Zone.current.handleUncaughtError(details.exception, details.stack); }; runZoned<Future<void>>(() async {  runApp(MyApp()); }, onError: (error, stackTrace) async {  await _reportError(error, stackTrace); });}Future<Null> _reportError(dynamic error, dynamic stackTrace) async { // TODO}

在 TODO 里面就可以執(zhí)行埋點上報操作或者其他處理了。

完整例子如下:

import 'dart:async';import 'package:flutter/material.dart';Future<Null> main() async { FlutterError.onError = (FlutterErrorDetails details) async {  Zone.current.handleUncaughtError(details.exception, details.stack); }; runZoned<Future<void>>(() async {  runApp(MyApp()); }, onError: (error, stackTrace) async {  await _reportError(error, stackTrace); });}Future<Null> _reportError(dynamic error, dynamic stackTrace) async { print('catch error='+error);}class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) {  return MaterialApp(   home: Scaffold(    appBar: AppBar(title: Text('Flutter Crash Capture'),),    body: MyHomePage(),   ),  ); }}class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) {  List<String> numList = ['1', '2'];  print(numList[6]);  return Container(); }}

運行可以看到控制臺捕獲到錯誤如下:

flutter: catch error=RangeError (index): Invalid value: Not in range 0..1, inclusive: 6

assert 妙用

我們知道,一般錯誤上報都是在打包發(fā)布到市場后才需要。

平時調(diào)試的時候如果遇到錯誤,我們是會定位問題并修復(fù)的。

因此在 debug 模式下,我們不希望上報錯誤,而是希望直接打印到控制臺。

那么,這個時候就需要一種方式來區(qū)分現(xiàn)在是 debug 模式還是 release 模式,怎么區(qū)分呢?

這個時候就需要用到 assert 了。

bool get isInDebugMode { // Assume you're in production mode. bool inDebugMode = false; // Assert expressions are only evaluated during development. They are ignored // in production. Therefore, this code only sets `inDebugMode` to true // in a development environment. assert(inDebugMode = true); return inDebugMode;}

從注釋也可以知道,assert 表達式只在開發(fā)環(huán)境下會起作用,在生產(chǎn)環(huán)境下會被忽略。

因此利用這一個,我們就可以實現(xiàn)我們的需求。

上面的結(jié)論要驗證也很簡單,我們就不演示了。

完整模板

import 'dart:async';import 'package:flutter/material.dart';Future<Null> main() async { FlutterError.onError = (FlutterErrorDetails details) async {  if (isInDebugMode) {   FlutterError.dumpErrorToConsole(details);  } else {   Zone.current.handleUncaughtError(details.exception, details.stack);  } }; runZoned<Future<void>>(() async {  runApp(MyApp()); }, onError: (error, stackTrace) async {  await _reportError(error, stackTrace); });}Future<Null> _reportError(dynamic error, dynamic stackTrace) async { // TODO}bool get isInDebugMode { // Assume you're in production mode. bool inDebugMode = false; // Assert expressions are only evaluated during development. They are ignored // in production. Therefore, this code only sets `inDebugMode` to true // in a development environment. assert(inDebugMode = true); return inDebugMode;}

debug 模式下,直接將錯誤打印到控制臺,方便定位問題。

release 模式下,將錯誤信息收集起來,上傳到服務(wù)器。

以上就是Flutter里面錯誤捕獲的正確方法,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI