Home > front end >  How to assign the non-nullable local variable "_msg"
How to assign the non-nullable local variable "_msg"

Time:05-14

I'm trying to make a Login form in flutter using a string function here is the code:

String validateEmail(String value) {
  String _msg;
  RegExp regex = RegExp(
      r'^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$');
  if (value.isEmpty) {
     _msg = "Your username is required";
  } else if (!regex.hasMatch(value)) {
     _msg = "Please provide a valid email address";
  }
  return _msg;
}

I get this error:

The non-nullable local variable '_msg' must be assigned before it can be used.

CodePudding user response:

The issue here is that you don't specify any else clause which means that in case of both your if's being false, the _msg will never get any value. That is a problem since the default value for any variable in Dart is null and the type String means we are not allow to set this variable to null.

So if no of the if-clauses are being executed, you would end up returning null.

Instead, this would be valid:

String validateEmail(String value) {
  String _msg;
  RegExp regex = RegExp(
      r'^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$');
  if (value.isEmpty) {
    _msg = "Your username is required";
  } else if (!regex.hasMatch(value)) {
    _msg = "Please provide a valid email address";
  } else {
    _msg = 'Some text';
    // throw Exception('Alternative, throw an error.');
  }
  return _msg;
}

(Yes, Dart is clever enough to recognise this pattern and will allow String _msg; in this case since it can safely ensure that _msg would always end up being given a value before we are using _msg.)

CodePudding user response:

When declaring your variables, make sure to instantiate them..

String _msg = "";

You can read more about flutter null safety here.

https://dart.dev/null-safety

CodePudding user response:

You can change this line

String _msg;

to this

late String _msg;
  •  Tags:  
  • dart
  • Related