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();
}
CodePudding user response:
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;
CodePudding user response:
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.
CodePudding user response:
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();
CodePudding user response:
Use late Future<Welcome> _welcome;
