Home > Mobile >  Flutter API keep loading and not showing
Flutter API keep loading and not showing

Time:12-28

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
    );
  }
}

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

CodePudding user response:

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.

CodePudding user response:

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 Article {
  List<Articles>? articles;

  Article({articles});

  Article.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 Articles {
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;

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

  Articles.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;
  }
}
  • Related