I was trying to make a News App with newsapi.org, but got this error:
The body might complete normally, causing 'null' to be returned,
but the return type, 'FutureOr<List<Article>>', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
Error from:
getArticle()
I've read a lot of ppl with the same problem and most of them told me to add return
or a throw
, which I already did but the error still appears.
So here's my code:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:medreminder/NewsArticle/models/article_models.dart';
class ApiService {
final endPointUrl =
"https://newsapi.org/v2/top-headlines?country=us&apiKey=cacee27fff544eb39d5fb29b28ca3788";
Future<List<Article>> getArticle() async {
Response res = await get(Uri.parse(endPointUrl));
if(res.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(res.body);
List<dynamic> body = json['articles'];
List<Article> articles =
body.map((dynamic item) => Article.fromJson(item)).toList();
} else {
throw("Cant get the News");
}
}
}
Let me know if you guys need to see my other code if necessary. Thank you guys
As the error states:
Try adding either a return or a throw statement at the end.
You need to return
something. In your case it's a List<Article>
.
I've read a lot of ppl with the same problem, most of them told to add return or a throw, which I already did but the error still appearing.
This is probably because you are adding the return statement within your if
/else
statement, so if your condition isn't met, then you still might not return anything.
To avoid the error, your code should look like this (null safe):
Future<List<Article>?> getArticle() async{
Response res = await get(Uri.parse(endPointUrl));
if(res.statusCode==200){
Map<String, dynamic> json = jsonDecode(res.body);
List<dynamic> body = json['articles'];
List<Article> articles = body.map((dynamic item) => Article.fromJson(item)).toList();
return articles;
}else{
return null;
}
}
Now, this function is nullable - which means that if the response is 200, it will return the articles
. Otherwise, it will return null