简体   繁体   中英

unhandled exception in flutter

the error has been caught but why these errors

onPressed: () {
            getName().then((value){
              print(value);
              print('The Last');
              throw('000');

            }).catchError((error){
              print('error (${error.toString()}) has been caught');
            });
        },

this is function

Future<String> getName() async
  {
    return 'Basel Elazaly';
  }
}

and these are output:

Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type

Add a throw in catch error like this

onPressed: () {
            getName().then((value){
              print(value);
              print('The Last');
              throw('000');

            }).catchError((error){
              print('error (${error.toString()}) has been caught');
              throw("some other error");//<--here 
            });
        },

Try this:

            onPressed: () {
              print(getName());
              print('The Last');
              throw('000');            
            },

Function

String getName()
  {
    return 'Basel Elazaly';
  }

It should work properly.

Just program for this century, using async / await instead of .then() . It will get a lot easier:

onPressed: () async {
       try {
         final value = await getName();
         print(value);
         print('The Last');
         throw('000');
        }
        catch(error){
          print('error (${error.toString()}) has been caught');
        }
    },

Official guidance: https://dart.dev/codelabs/async-await#handling-errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM