0

I have created a seperate class "DirectionDetails" which is;

class DirectionDetails{

  int distanceValue;
  int durationValue;
  String distanceText;
  String durationText;
  String encodedPoints;

  DirectionDetails(this.distanceValue, this.durationValue, this.distanceText, this.durationText, this.encodedPoints);

}

When I try to initialize that in the main class by DirectionDetails tripDirectionDetails;, it gives the

Non-nullable instance field 'tripDirectionDetails' must be initialized

error. But as it suggest, when I add "late" modifier - it dosen't show any errors but when i run the app it gives the,

LateInitializationError: Field 'tripDirectionDetails' has not been initialized.

runtime error

There is an alternative method I tried, when i try to initialize tripDirectionDetails in main class using,

DirectionDetails tripDirectionDetails = new DirectionDetails();

and modify DirectionDetails class by,

class DirectionDetails{

  int distanceValue;
  int durationValue;
  String distanceText;
  String durationText;
  String encodedPoints;

  DirectionDetails({this.distanceValue = 0, this.durationValue = 0, this.distanceText = "", this.durationText = "", this.encodedPoints = ""});
  
}

App runs successfully, it retrieves all the vales in "DirectionDetails" class only for the initial reboot.

But when I exit the app and come back, it gives the following error.

LateInitializationError: Field 'tripDirectionDetails' has not been initialized.

Your help is much appreciated.

Thank you

  • Can you show where the `tripDirectionDetails ` is being used? – John Oyekanmi Jul 19 '21 at 12:18
  • @JohnOyekanmi Text(((tripDirectionDetails!= null) ? tripDirectionDetails.durationText : '') , style: TextStyle(fontSize: 16.0, color: Colors.grey),), – Manodhya Opallage Jul 19 '21 at 12:26
  • Okay, I assume the widget in which this is being used is a StatefulWidget. If that's the case try initializing the field, `tripDirectionDetails`, at the initState method before making use of it anywhere. Something like this `tripDirectionDetails = DirectionDetails()`. – John Oyekanmi Jul 19 '21 at 12:31

1 Answers1

0

That is happening because you are trying to use tripDirectionDetails before initializing it. You should use late only for non null variables that will be initialized later before trying to use:

tripDirectionDetails != null /// This will trigger an error

You should initialize it before using it on build or in initState:

@override
  void initState() {
    tripDirectionDetails = DirectionDetails();
    super.initState();
  }

But as tripDirectionDetails can be null, it would be better to declare it like this:

DirectionDetails? tripDirectionDetails;

tripDirectionDetails != null /// Won't trigger an error
NelsonThiago
  • 802
  • 7
  • 12