Home > database >  "The body might complete normally, causing 'null' to be returned, but the return type
"The body might complete normally, causing 'null' to be returned, but the return type

Time:12-27

i was trying to make a News App with newsapi.org, but got the 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 in

 getArticle()

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.

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 needs to see my other code if necessary. thankyou guys

CodePudding user response:

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();
    }else{

      throw("Cant get the News");
    }

  }

Now, this function is nullable - which means that if the response is 200, it will return the articles. Otherwise, it will return null

  • Related