This is because of null safety in Dart. There are a lot of guides out there written before null safety was introduced.
It is ok to declare a class member as nullable with the ?, so this is valid, and means that i can have the value null, therefore it is allowed without initialising its value:
int? i;
If you don't use the ?, you can still declare a member, but you have to assign a value to it, this is also valid:
int i=1;
But this will be invalid, since you say that i can't be null, and you do not assign a value to it:
int i;
And here comes the late keyword. By using this you "promise" Dart, that you will initialise this value later, for example in an initState method like this:
class MyWidget extends StatefulWidget {
const MyProfile({Key? key}) : super(key: key);
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late int _i;
@override
void initState() {
super.initState();
_i = 1;
}
You have to keep this "promise", otherwise you will get a runtime error.
Another option is that you create a constructor for the class that has required members, it will ensure that these values can't miss in any instance created, so Dart is ok with it:
class MyClass {
int i;
MyClass({required this.i});
}
In this last example, if you omit required keyword, you will get an error, because i is not nullable, and if it is not required by the constructor, it could be null. Still, it will work without required, if you make i nullable by declaring it like int? i;.