1

So i tried to create a listview of a news with this API https://newsapi.org/s/us-news-api but when i tried to implement it in my App it keeps loading and never show the data.

here is my homepage code

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:medreminder/NewsArticle/components/list_tile.dart';
import 'package:medreminder/NewsArticle/models/article_models.dart';
import 'package:medreminder/NewsArticle/services/api_service.dart';

class NewsHomePage extends StatelessWidget {
  //const NewsHomePage({super.key});

  ApiService client = ApiService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Get.isDarkMode?Colors.grey[600]:Colors.white,
        leading: IconButton(
          onPressed: ()=>Get.back(),
          icon: Icon(Icons.arrow_back_ios,
          color: Get.isDarkMode?Colors.white:Colors.grey
          ),
        ),
        title:  Text("News & Article", style: TextStyle(
          color: Get.isDarkMode?Colors.white:Colors.black
        ),),
      ),
      body: FutureBuilder(
        future: client.getArticle(),
        builder: (BuildContext context, AsyncSnapshot<List<Article>> snapshot) {
          if(snapshot.hasData){
            List<Article>? articles = snapshot.data;
            return ListView.builder(
              itemCount: articles!.length,
              itemBuilder: (context, index) => listTile(articles[index])
            );
          }
          return Center(child: CircularProgressIndicator(),);
        },
      ),
    );
  }
}

my API Service

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

      throw("Cant get the News");
    }

  }
}

here is my model class

import 'source_models.dart';

class Article{
  Source source;
  String author;
  String title;
  String description;
  String url;
  String urlToImage;
  String publishedAt;
  String content;

  Article({
    required this.source,
    required this.author,
    required this.title,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.publishedAt,
    required this.content
  });

  factory Article.fromJson(Map<String, dynamic> json){
    return Article(
      source: Source.fromJson(json['source']), 
      author: json['author'] as String, 
      title: json['title'] as String, 
      description: json['description'] as String, 
      url: json['url'] as String, 
      urlToImage: json['urlToImage'] as String, 
      publishedAt: json['publishedAt'] as String, 
      content: json['content'] as String
    );
  }
}

Adding my customtile code

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:medreminder/NewsArticle/models/article_models.dart';

Widget listTile(Article article){
  return Container(
    margin: EdgeInsets.all(12),
    padding: EdgeInsets.all(8),
    decoration: BoxDecoration(
      color: Get.isDarkMode?Colors.white:Colors.black,
      borderRadius: BorderRadius.circular(18),
      boxShadow: [
        BoxShadow(
          color: Get.isDarkMode?Colors.white:Colors.black,
          blurRadius: 3
        )
      ]
    ),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(article.urlToImage)
            ),
            borderRadius: BorderRadius.circular(8),

          ),
        ),
        SizedBox(height: 9),
        Container(
          decoration: BoxDecoration(
            color: Colors.red,
            borderRadius: BorderRadius.circular(30),
          ),
          child: Text(article.source.name),
        ),
        SizedBox(height: 8,),
        Text(article.title, style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 16,
        ),)
      ],
    ),
  );
}

i dont know how this happening but i followed everysecond in a yt tutorial but still got this never stop loading. let me know if you guys needs to see my other codes if necessary. thankyou guys

4
  • please can you check you are getting data properly in you model class variable and articles returning its properly? Commented Dec 27, 2022 at 4:58
  • hellos sir, i have added my model class in my question. thankyou Commented Dec 27, 2022 at 6:50
  • First of all check that, are you getting response, print your response in console?. and if yes, once you get response, are you updating states ? Commented Dec 28, 2022 at 6:51
  • i have tried that, and didnt get the response Commented Dec 29, 2022 at 6:36

2 Answers 2

1

I check your code, you have to update your Article class. Because some values are null in API response, so that causes issue. To handle that You have to generate dart model class for APIs response by using json to dart convertor.

Here is updated class:

class Articles {
  List<Articles>? articles;

  Articles({this.articles});

  Articles.fromJson(Map<String, dynamic> json) {
    if (json['articles'] != null) {
      articles = <Articles>[];
      json['articles'].forEach((v) {
        articles!.add(Articles.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (articles != null) {
      data['articles'] = articles!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Article {
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;

  Article(
      {source,
      author,
      title,
      description,
      url,
      urlToImage,
      publishedAt,
      content});

  Article.fromJson(Map<String, dynamic> json) {
    source = json['source'] != null ? Source.fromJson(json['source']) : null;
    author = json['author'];
    title = json['title'];
    description = json['description'];
    url = json['url'];
    urlToImage = json['urlToImage'];
    publishedAt = json['publishedAt'];
    content = json['content'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (source != null) {
      data['source'] = source!.toJson();
    }
    data['author'] = author;
    data['title'] = title;
    data['description'] = description;
    data['url'] = url;
    data['urlToImage'] = urlToImage;
    data['publishedAt'] = publishedAt;
    data['content'] = content;
    return data;
  }
}

class Source {
  String? id;
  String? name;

  Source({id, name});

  Source.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['name'] = name;
    return data;
  }
}

and listTile widget will be :

 Widget listTile(Article article) {
  return Container(
    margin: EdgeInsets.all(12),
    padding: EdgeInsets.all(8),
    decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(18),
        boxShadow: [BoxShadow(color: Colors.black, blurRadius: 3)]),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(image: NetworkImage(article.urlToImage!)),
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        SizedBox(height: 9),
        Container(
          decoration: BoxDecoration(
            color: Colors.red,
            borderRadius: BorderRadius.circular(30),
          ),
          child: Text(article.source!.name!),
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          article.title!,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 16,
          ),
        )
      ],
    ),
  );
}
Sign up to request clarification or add additional context in comments.

10 Comments

using ur code, i cant call the title, source and urlToImage in my custom tile class. im able to fix the error by creating a getter, but when i run it, it shows a stack overflow error. how do i fix this sir? thankyou
Can you please add code of your custom class. So I can help further
hello sir, i've added my customtile class got a red underline in "urlToImage, source, and title" thankyou
In ListTile widget replace it to "Articles" not just "Article" -> Widget listTile(Articles article)" also as you have some null values you have to handle null values in ListTile widget. I have also updated code in my answer
hello sir, i have opened another question regarding this issue, but i will still accept your answer as the right one, feel free to check my other question here stackoverflow.com/questions/74957550/… so you might get 2 accepted answers for my problem :) thankyou so much sir
|
0

I run this API in postman and get response in html format. There in response they mentioned to get reponse by this API https://newsapi.org/v2/top-headlines?country=gb&apiKey=API_KEY

Try this one, Maybe it works.

2 Comments

still the same sir, doesnt work
Do you have a valid API key? What response do you get this time? Try on Postman first then implement in app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.