Home > OS >  The body might complete normally, causing 'null' to be returned, but the return type, 
The body might complete normally, causing 'null' to be returned, but the return type, 

Time:01-16

I want to add conditional for image but it show an error on _setImage(), how to fix it?

The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type. Try adding either a return or a throw statement at the end.

  class _SplashScreenState extends State<SplashScreen> {
      final String appName = AppConfig.appName;
    
      String _setImage() {
      if(appName.isNotEmpty == '') {
        return 'assets/something1.png';
      } else if(appName.isNotEmpty == '') {
        return 'assets/something2.png';
      } 
      }
     
      @override
      Widget build(BuildContext context) {
       return Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                    fit: BoxFit.cover,
                    image: AssetImage(_setImage()) //call your method here
                ),
              ),
            );
      }
    }

CodePudding user response:

It's because appName.isNotEmpty is already a condition.

To fix:

String _setImage() {
  if(appName.isNotEmpty) {
    return 'assets/something1.png';
  } else {
    return 'assets/something2.png';
  } 
}

CodePudding user response:

isNotEmpty is a getter and returns a boolean value that's why you can simply call it without adding further condition to it.

String _setImage() { 
           return appName != null && appName.isNotEmpty ? 'assets/something1.png' : 'assets/something2.png';
  }

CodePudding user response:

appName.isNotEmpty is already a condition.

Change your code like this :

 if(appName.isNotEmpty) {
   return 'assets/something1.png';
 } 

 return 'assets/something2.png';

CodePudding user response:

It is showing this error because your function's return type is String which is non-nullable.

You have't write the code for if neither of your conditions gets true then what to return.

Following are two solutions for it.

  1. Try to make _setImage()'s return a nullable String. So function's return type should be String? Like following code snippet.

      String? _setImage() {
          if(appName.isNotEmpty == '') {
            return 'assets/something1.png';
          } else if(appName.isNotEmpty == '') {
            return 'assets/something2.png';
         } 
      }
    

    OR

  2. Return a String at every place where your function can possibly return.

     String _setImage() {
              if(appName.isNotEmpty == '') {
                return 'assets/something1.png';
              }
             return 'assets/something3.png'; //Default image if neither of the conditions gets satisfied.
          }
    

However, I recommend you to use this package another_flutter_splash_screen 1.1.4 as it is highly customizable for splash screens.

  • Related