Home > Blockchain >  Flutter functions Null safety errors
Flutter functions Null safety errors

Time:11-23

Got the following errors and don't know how to update the code to solve it.

Error: Can't use an expression of type 'Function?' as a function because it's potentially null.

  • 'Function' is from 'dart:core'. Try calling using ?.call instead. PageName nextPage = pageName_pageFunction_mapPageName.welcomePage; PageName nextPage2 = pageName_pageFunction_mapnextPage;

The code:

enum PageName {
  welcomePage,
  register,
  login,
  editProfile,
  showProfile,
  resetPassword,
  errorUserExists,
}

Map<PageName, Function> pageName_pageFunction_map = {
  PageName.welcomePage: showWelcomePage,
  PageName.register: showRegisterPage,
  PageName.login: showLoginPage,
  PageName.editProfile: showEditProfile,
  PageName.showProfile: showUserProfile,
  PageName.resetPassword: showResetPassword,
  PageName.errorUserExists: showErrorUserExists,
};

void main() {
    PageName nextPage = pageName_pageFunction_map[PageName.welcomePage]();
    if (nextPage != null) {
      while (true) {
        PageName nextPage2 = pageName_pageFunction_map[nextPage]();
        if (nextPage2 != null) {
          nextPage = nextPage2;
        }
      }
    }
}

Can you help me? Thank you

CodePudding user response:

The error message tell that you can't execute a function because this one might be null, and if you execute a function on a null value it will break the program. You have two solution :

First you can make sure that your function isn't null with a test :

if (myFunction != null) {
  myFunction()
}

Or you can tell the compiler that your function is not null with the ! operator

myFunction!()

CodePudding user response:

Error: Can't use an expression of type 'Function?' as a function because it's potentially null.

When you look up one of your functions from the map like pageName_pageFunction_map[PageName.welcomePage] you get a value of type Function?. This is because if you enter a key which does not have a corresponding value, you will get back null from the expression.

The following error message gives you a suggestion on how to solve this problem.

'Function' is from 'dart:core'. Try calling using ?.call instead. PageName nextPage = pageName_pageFunction_mapPageName.welcomePage; PageName nextPage2 = pageName_pageFunction_mapnextPage;

You can place ?.call directly before the argument list () to safely call the function;

pageName_pageFunction_map[PageName.welcomePage]?.call();
  • Related