Home > Software engineering >  Flutter list function execute error management
Flutter list function execute error management

Time:10-02

in a flutter, I execute multiple functions on initState. Like this:-

  @override
  void initState() {
    super.initState();
    function1();
    function2();
    function3();
    function4();
  }

in case the function2() has some errors it affects function3(),function4() also. How do we avoid this?

CodePudding user response:

You can call try in each functions to avoid getting stop incase of getting error:

void function1(){
    try {
      //put you code hear
    } catch (e) {
      print("e = $e");
    }
}

CodePudding user response:

You have to use try & catch but, there is a way to write only at one place !

create a extension on Function to call it & absorb the error if any occures in it.

Here is a example:

import 'dart:developer';

void f1() => print('f1');

void f2() => throw 'STOP';

void f3() => print('f3');

extension FunctionUtils on Function {
  void callAndAbsorbError() {
    try {
      this.call();
    } catch (e, st) {
      log("Error in $this", error: e, stackTrace: st);
    }
  }
}

void main(List<String> arguments) {
  f1.callAndAbsorbError();
  f2.callAndAbsorbError();
  f3.callAndAbsorbError();
}

This way you don't need to write try catch in every function you create. AND all your functions will execute for sure.

More about extensions : vandad's blog

  • Related