How to convert these block of codes into non-nullable statement/s in dart?

11,898

Solution 1

Try this

child: BlocBuilder<LoginBloc, LoginState>(
                builder: (context, state) {
                  if (state is LoginInitialState) {
                    return buildInitialUi();
                  } else if (state is LoginLoadingState) {
                    return buildLoadingUi();
                  } else if (state is LoginFailState) {
                    return buildFailureUi(state.message);
                  } else if (state is LoginSuccessState) {
                    emailCntrlr.text = "";
                    passCntrlr.text = "";
                    return Container();
                  }
                  return Container(); // In case none of the if statements is true
                },
              ),

Solution 2

Try This

After String add "?" and return null; Like This

class ValidationMixin {
  String? validateEmail(String value) {
    if (!value.contains('@')) {
      return 'Please enter a Valid Email';
    }
    return null;
  }
}
Share:
11,898

Related videos on Youtube

Nikash Deka
Author by

Nikash Deka

Updated on June 04, 2022

Comments

  • Nikash Deka
    Nikash Deka almost 2 years

    I am trying to convert these lines of code into non-nullable statements, but encountering the error...

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

                 child: BlocBuilder<LoginBloc, LoginState>(
                    builder: (context, state) {
                      if (state is LoginInitialState) {
                        return buildInitialUi();
                      } else if (state is LoginLoadingState) {
                        return buildLoadingUi();
                      } else if (state is LoginFailState) {
                        return buildFailureUi(state.message);
                      } else if (state is LoginSuccessState) {
                        emailCntrlr.text = "";
                        passCntrlr.text = "";
                        return Container();
                      }
                    },
                  ),
    
    • Julia
      Julia about 3 years
      Couldn't you do what the error message says and add a throw statement at the end?
  • Nikash Deka
    Nikash Deka about 3 years
    It worked, thanks. However, while accessing the property of the state (i.e., state.message), an error occurred... "The argument type 'String?' can't be assigned to the parameter type 'String'." After the null-safety upgrade in the SDK I am finding such errors in many places!
  • YoBo
    YoBo about 3 years
    you can set default value if the message is nullable: state.message ?? ''
  • Nikash Deka
    Nikash Deka about 3 years
    How to use packages that are not upgraded to null-safety?