I've been trying to initial string _cityEntered to use into all my widgets. As you can see i've intialized using late keyword. And then i've initialized the string into if statement. But when i'm running the code i'm getting this error everytime. It's saying i've not initialized the string. LateInitializationError: Field '_cityEntered@20328536' has not been initialized.
class _ClimaticState extends State<Climatic> {
late String _cityEntered;
Future _goToNextScreen(BuildContext context) async {
Map results = await Navigator.of(context)
.push(MaterialPageRoute<dynamic>(builder: (BuildContext context) {
return CityWeather();
}));
if (results != null && results.containsKey("enter")) {
_cityEntered = results["enter"];
// print(results['enter'].toString());
}
}
CodePudding user response:
You are intilizing only if results != null && results.containsKey("enter")
condition is meet, but other cases it will not assinged.
make it nullable
String? _cityEntered;
While using _cityEntered
check if it is null, like
if(_cityEntered!=null) doYourStuff
Or provide default value on null cases like
_cityEntered?? "default value"
CodePudding user response:
It is because you are promising the compiler that you will initialize the _cityEntered
but it happens only if results != null && results.containsKey("enter")
condition is met.
So the compiler is throwing the error. To overcome this just
Change
late _cityEntered name;
to
String? _cityEntered;