'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();
}
Solution 1:[1]
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;
Solution 2:[2]
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.
Solution 3:[3]
Use late Future<Welcome> _welcome;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ogün Birinci |
| Solution 2 | Robiness |
| Solution 3 | Aravind Aji |
