Flutter, late keyword with declaration

Declare variables that will be initialised later by using the late keyword.

late data_type variable_name;

When a late variable is used before it has been initialised, this error happens. You must keep in mind that although you used some variables or data that were marked as “late,” their values were not altered or saved beforehand.

late String name;
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Text(name)
    //runtime error: 
    //LateInitializationError: Field 'name' has not been initialized.
  );
} 

This signifies that the variable name has no value at this time; it will be initialised in the Future. We have used this variable in the Text() widget without first initialising it.

To fix this problem

late String name;

@override
void initState() {
  name = "Flutter Campus";
  super.initState();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Text(name)
  );
} 

Leave a Comment