Add News using NewsApi Flutter

242 Views Asked by At

So i am building a news page for my app , but i am unable to add news using the news api i have made the function that extracts and adds News to the BreakingNews ( basically the headlines ) and the RecentNews Lists

import 'package:vitactivity/models/News.dart';

class ArticleModel {
  String? title;
  String? author;
  String? content;
  String? urlToImage;
  String? date;
  String url;

  //let's create the constructor
  ArticleModel(this.title, this.author, this.content, this.date,
      this.urlToImage, this.url);

  static List<ArticleModel> breakingNews = [...]; // i have some dummy data here
  static List<ArticleModel> recentNews = [...]; // i have some dummy data here
}

i have written the other function that extracts and adds data to the list until a desired length is achieved but i cant figure out how do i call this function correctly so i can actually have the news added ( i am probably very dumb )

import 'package:http/http.dart' as http;
import 'package:vitactivity/models/ArticleModel.dart';
import 'dart:convert';

class News {
  Future<void> getNews(int a) async {
    while (ArticleModel.breakingNews.length <= a) {
      String url =
          "http://newsapi.org/v2/top-headlines?country=in&catagory=health&sortBy=publishedAt&language=en&apiKey=Apikey"; // using the correct api key and gives me results on chrome as well

      var response = await http.get(Uri.parse(url));

      var jsonData = jsonDecode(response.body);

      if (jsonData['status'] == "ok") {
        jsonData["articles"].forEach((element) {
          if (element['urlToImage'] != null && element['description'] != null) {
            ArticleModel article = ArticleModel(
              element['title'],
              element['author'],
              //element['description'],
              element['urlToImage'],
              element['publishedAt'],
              element["content"],
              element["url"],
            );
            ArticleModel.breakingNews.add(article);
          }
        });
      }
    }
  }
}

The Ui with the Dummy works fine

i have tried to write the function that calls the getNews function but everything is giving me errors and cant even find anything on the internet , every thing seems very complex to figure out on my own without the documentation

i wrote this inti function to get the the news added but nothing is happening

void initState() {
News().getBreakingNews(5);
News().getRecentNews(10);
super.initState();

}

0

There are 0 best solutions below