TransWikia.com

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

Stack Overflow Asked by princeoo7 on February 18, 2021

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…

2 Answers

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

Correct answer by krishnakumarcn on February 18, 2021

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

Answered by nvoigt on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP