is it a good idea to use // ignore: missing_return in an future fuction where we are using conditioning to return answer?

379

Solution 1

The warnings like this actually help you to write clean error-free code. Don't ever try to ignore them, Try to fix them by understanding it.

Your function getProfile() expecting a Future<UserModel> as its return type.

Yes, you are returning a UserModel on the else condition, but you are not returning anything from the function if the condition (_user == null) is true.

Based on your use case, you could do something like,

 Future<UserModel> getProfile() async {
    if (_user == null) {
      /// sets the _user if its null
      _user = await Provider.of<UserProvider>(context).fetchUserProfile();
    } 

    ///returns the _user
    return _user;
   
  }

Solution 2

No, that's bad. Someone told you there is a problem and instead of fixing the problem you told them to shut up. Your compiler won't take it personally, but it's still not a good move to write quality code.

You are missing a return. In other languages, this would be a compiler error, not a warning. Your code is flawed. You need to fix it.

You said your method returns a UserModel and if _user is null, it simple doesn't.

Since I don't know what you want to happen, I can only make suggestions. I guess you want this method to return the user and load it if it has not been loaded yet. So this would be your proper way of doing it:

Future<UserModel> getProfile() async {
    if (_user == null) {
      _user = await Provider.of<UserProvider>(context).fetchUserProfile();
    } 
      
    return _user;
}
Share:
379
princeoo7
Author by

princeoo7

Updated on December 24, 2022

Comments

  • princeoo7
    princeoo7 over 1 year

    As the question state, is it a good idea to use // ignore: missing_return above the future function where we are using conditions to return answer.

    e.g.

     Future<UserModel> getProfile() async {
        if (_user == null) {
          _user = await Provider.of<UserProvider>(context).fetchUserProfile();
        } else {
          return _user;
        }
      }
    

    the warning is suppressed when done as below:

    // ignore: missing_return
      Future<UserModel> getProfile() async {
        if (_user == null) {
          _user = await Provider.of<UserProvider>(context).fetchUserProfile();
        } else {
          return _user;
        }
      }
    
    

    is this a good practice or what modification should I do to the given code...