Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The correct method of error trapping in Flutter

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What this article shares to you is about the correct method of error trapping in Flutter. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Background

We know that errors and exceptions are always inevitable in the process of software development.

Whether it is caused by a logic error on the client or a data problem on the server, whenever there is an exception, we need a mechanism to inform us to deal with it.

In the development process of APP, we can report exceptions through some third-party platforms, such as Fabric, Bugly and so on.

Flutter also has some third-party platforms, such as Sentry, which can implement log reporting of exceptions.

But in order to be more general, this article does not specifically explain how to catch exceptions in conjunction with the exception log capture of a third-party platform, we will show you how to catch exceptions in Flutter.

As for the specific reporting methods, it is possible to report exceptions to your own background server or through the third-party SDK API interface.

Demo initial state

First, we create a new Flutter project and modify the main.dart code as follows:

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 ();}}

The effect is as follows:

Catch error

We modify the MyHomePage, add a List, and then access it out of bounds. Change part of the code as follows:

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

You can see that the console reported an error as follows:

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

Of course, these error messages are also displayed on the interface (debug mode).

So how do we capture it?

In fact, it is very simple, there is a general template, the template is:

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

You can perform burying point reporting operation or other processing in TODO.

The complete example is as follows:

Import 'dart:async';import' package:flutter/material.dart';Future main () async {FlutterError.onError = (FlutterErrorDetails details) async {Zone.current.handleUncaughtError (details.exception, details.stack);}; runZoned (() async {runApp (MyApp ());}, onError: (error, stackTrace) async {await _ reportError (error, stackTrace);}) Future _ 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 numList = [' 1levels,'2']; print (numList [6]); return Container ();}}

If you run it, you can see that the console caught the error as follows:

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

Ingenious use of assert

We know that general error reporting is only needed after it has been packaged and released to the market.

If we encounter an error during debugging, we will locate the problem and fix it.

So in debug mode, we don't want to report errors, but we want to print them directly to the console.

So, at this point, you need a way to tell the difference between debug mode and release mode.

At this point, you need to use 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;}

You can also know from the comments that assert expressions work only in the development environment and are ignored in the production environment.

So with this one, we can meet our needs.

The above conclusion is also very simple to verify, so we will not demonstrate it.

Complete template

Import 'dart:async';import' package:flutter/material.dart';Future main () async {FlutterError.onError = (FlutterErrorDetails details) async {if (isInDebugMode) {FlutterError.dumpErrorToConsole (details);} else {Zone.current.handleUncaughtError (details.exception, details.stack);}}; runZoned (() async {runApp (MyApp ());}, onError: (error, stackTrace) async {await _ reportError (error, stackTrace);}) } Future _ 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;}

In debug mode, the error is printed directly to the console to facilitate the positioning of the problem.

In release mode, the error messages are collected and uploaded to the server.

The above is the correct way to catch errors in Flutter. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report