Panashe
Panashe

Reputation: 139

Non-nullable instance field 'Welcome' must be initialized Flutter

I am trying to call API's in flutter but when I am defining the variable _Welcome I am getting this error. Does anyone know how to fix it?

class _PostsPageState extends State<PostsPage> {
Future<Welcome> _Welcome; //error here


@override
void initState() {
_Welcome = API_Manager().getNews();
super.initState();
}

Upvotes: 3

Views: 294

Answers (4)

Stijn2210
Stijn2210

Reputation: 884

Your Future is not used with the late keyword, so the Dart analyzer expects it to be instantly initialized.

Either do:

late Future<Welcome>. _Welcome;

@override
void initState() {
_Welcome = API_Manager().getNews();
super.initState();
}

or just at the start:

Future<Welcome> _Welcome = API_Manager().getNews();

Upvotes: 1

Aravind Aji
Aravind Aji

Reputation: 154

Use late Future<Welcome> _welcome;

Upvotes: 0

Robiness
Robiness

Reputation: 79

try late Future<Welcome> _Welcome;

With this you promise to the compiler that it is initialized when it's accessed later on. Since you assing it directly in the initState that is fine.

Upvotes: 0

Og&#252;n Birinci
Og&#252;n Birinci

Reputation: 728

This error due to the null-safety property of flutter. So, what is null-safety? Flutter null safety is the feature that became available after the release of version 2. This feature helps to improve developers' productivity by eliminating a whole class of bugs caused by null dereferencing errors. So, how can you solve this problem? Actually, there are many options for that; you can initialize the variable at the time of the declaration, or you can use late keyword such as late Future<Welcome> _Welcome;

Upvotes: 0

Related Questions