Home > OS >  Conditional return gives warning in Flutter
Conditional return gives warning in Flutter

Time:03-31

My function has a return statement that is only triggered when the function succeeds ( in this case the user doesn't allow access to camera or gallery ).

  Future<String> getImageFrom(ImageSource source) async {
    try {
      XFile xfile = await ImagePicker().pickImage(
        source: source,
      );
      return xfile.path;
    } on PlatformException catch (e) {
      debugPrint('Failed to pick image: $e');
    }
  }

I get the warning:

This function has a return type of 'FutureOr<String>', but doesn't end with a return statement.

But i don't understand what i could return in the Exception that would make sense. I have 2 other function similar to this so I would like to understand what is the correct way to deal with this issue.

The only thing that occurs to me is returning empty responses and then check the return value in the place where the function is called. Is there a better way?

CodePudding user response:

Ask yourself this question: Should my program crash when this exception is encountered? If not, what should it do?

Based on the answer, you can determine what you should return from this function. If your program should keep on running, you will indeed have to return some sort of null value and check that on the callers' end, there isn't really another feasible option, because all of the consumers of your function might do different stuff with the output data.

CodePudding user response:

Add the return out side the try scope:

  Future<String> getImageFrom(ImageSource source) async {
    XFile? xfile;
    try {
      xfile = await ImagePicker().pickImage(
        source: source,
      );
    } on PlatformException catch (e) {
      debugPrint('Failed to pick image: $e');
    }
     return xfile.path;
  }
  • Related