Flutter-API call (News app)

When we think about any famous app then we have to think about data change dynamically change from server and it can possible using API call to server and display data to app. Here, Flutter App with API call.

You can Download Source Code via Github.

First of all we will generate API key for call news API as per following steps

  1. Click here to open link
  2. Click on “Get API key” button
  3. After generate API key you can use API for News ” http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=YOUR API KEY”

Needed lib in .yaml file

dio: ^2.0.15
progress_dialog: ^1.2.0

API Call

Future<int> dioCall() async {
    loadingView();
    try {
      Response response = await Dio().get(
          "http://newsapi.org/v2/top-headlines?sources=google-news&apiKey=c06c776c356f4cfd9eef7fdb4e3c26ac");
      print(response);
      final newsModel = newsModelFromJson(response.toString());

      var list = newsModel.toJson()['articles'] as List;
      List<News> newsList = list.map((i) => News.fromJson(i)).toList();
      List<NewsInsert> newsInsertTemp = [];
      newsInsertTemp.clear();
      for (var i = 0; i < newsList.length; i++) {
        print("i data:${i}");
        NewsInsert insert = new NewsInsert(
            newsList[i].title,
            newsList[i].description,
            newsList[i].description,
            newsList[i].urlToImage);
        newsInsertTemp.add(insert);
      }
      newsInsert.clear();
      setState(() {
        newsInsert.addAll(newsInsertTemp);
      });
    } catch (e) {
      print(e);
    }
    return 10;
  }

Model class

import 'dart:convert';

NewsModel newsModelFromJson(String str) {
  final jsonData = json.decode(str);
  return NewsModel.fromJson(jsonData);
}

String newsModelToJson(NewsModel data) {
  final dyn = data.toJson();
  return json.encode(dyn);
}

class NewsModel {
  String status;
  int totalResults;
  List<News> articles;

  NewsModel({
    this.status,
    this.totalResults,
    this.articles,
  });

  factory NewsModel.fromJson(Map<String, dynamic> json) => new NewsModel(
    status: json["status"] == null ? null : json["status"],
    totalResults: json["totalResults"] == null ? null : json["totalResults"],
    articles: json["articles"] == null ? null : new List<News>.from(json["articles"].map((x) => News.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "status": status == null ? null : status,
    "totalResults": totalResults == null ? null : totalResults,
    "articles": articles == null ? null : new List<dynamic>.from(articles.map((x) => x.toJson())),
  };
}

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

  News({
    this.author,
    this.title,
    this.description,
    this.url,
    this.urlToImage,
    this.content,
    this.source,
  });

  factory News.fromJson(Map<String, dynamic> json) => new News(
    author: json["author"] == null ? null : json["author"],
    title: json["title"] == null ? null : json["title"],
    description: json["description"] == null ? null : json["description"],
    url: json["url"] == null ? null : json["url"],
    urlToImage: json["urlToImage"] == null ? null : json["urlToImage"],
    content: json["content"] == null ? null : json["content"],
    source: json["source"] == null ? null : Source.fromJson(json["source"]),
  );

  Map<String, dynamic> toJson() => {
    "author": author == null ? null : author,
    "title": title == null ? null : title,
    "description": description == null ? null : description,
    "url": url == null ? null : url,
    "urlToImage": urlToImage == null ? null : urlToImage,
    "content": content == null ? null : content,
    "source": source == null ? null : source.toJson(),
  };
}

class Source {
  String id;
  String name;

  Source({
    this.id,
    this.name,
  });

  factory Source.fromJson(Map<String, dynamic> json) => new Source(
    id: json["id"] == null ? null : json["id"],
    name: json["name"] == null ? null : json["name"],
  );

  Map<String, dynamic> toJson() => {
    "id": id == null ? null : id,
    "name": name == null ? null : name,
  };
}

Custom Listview layout

class NewsSummary extends StatelessWidget {

  final NewsInsert news;
  final bool horizontal;

  NewsSummary(this.news, {this.horizontal = true});

  NewsSummary.vertical(this.news): horizontal = false;


  @override
  Widget build(BuildContext context) {

    final newsThumbnail = new Container(
      margin: new EdgeInsets.symmetric(
        vertical: 10.0
      ),
      alignment: horizontal ? FractionalOffset.centerLeft : FractionalOffset.center,
      child: new Hero(
          tag: "news-hero-${news.title}",
          child: new Container(
              width: 100.0,
              height: 100.0,
              decoration: new BoxDecoration(
                  shape: BoxShape.circle,
                  image: new DecorationImage(
                      fit: BoxFit.fill,
                      image: new NetworkImage(
                          news.imglink)
                  )
              )),
      ),
    );



    final newsCardContent = new Container(
      margin: new EdgeInsets.fromLTRB(horizontal ? 76.0 : 16.0, horizontal ? 16.0 : 42.0, 16.0, 16.0),
      constraints: new BoxConstraints.expand(),
      child: new Column(
        crossAxisAlignment: horizontal ? CrossAxisAlignment.start : CrossAxisAlignment.center,
        children: <Widget>[
          new Container(height: 4.0),
          new Text(news.title, style: TextStyle(color: Colors.white,
              fontSize: 15.0,
              fontWeight: FontWeight.w600),
            overflow: TextOverflow.ellipsis,
            maxLines: 4,),
        ],
      ),
    );


    final newsCard = new Container(
      child: newsCardContent,
      height: horizontal ? 124.0 : 154.0,
      margin: horizontal
        ? new EdgeInsets.only(left: 46.0)
        : new EdgeInsets.only(top: 72.0),
      decoration: new BoxDecoration(
        color: new Color(0xFF333366),
        shape: BoxShape.rectangle,
        borderRadius: new BorderRadius.circular(8.0),
        boxShadow: <BoxShadow>[
          new BoxShadow(
            color: Colors.black12,
            blurRadius: 10.0,
            offset: new Offset(0.0, 10.0),
          ),
        ],
      ),
    );


    return new GestureDetector(
      onTap: horizontal
          ? () => Navigator.of(context).push(
            new PageRouteBuilder(
              pageBuilder: (_, __, ___) => new DetailPage(news),
              transitionsBuilder: (context, animation, secondaryAnimation, child) =>
                new FadeTransition(opacity: animation, child: child),
              ) ,
            )
          : null,
      child: new Container(
        margin: const EdgeInsets.symmetric(
          vertical: 16.0,
          horizontal: 24.0,
        ),
        child: new Stack(
          children: <Widget>[
            newsCard,
            newsThumbnail,
          ],
        ),
      )
    );
  }
}

You can Download Source Code via Github.

7 Replies to “Flutter-API call (News app)”

  1. Hi there i am kavin, its my first occasion to commenting anyplace,
    when i read this article i thought i could also make comment
    due to this good piece of writing.

  2. An interesting discussion is definitely worth comment.
    I do believe that you need to write more on this
    topic, it may not be a taboo matter but typically people don’t discuss such issues.

    To the next! Many thanks!!

  3. I have learn several just right stuff here.

    Certainly price bookmarking for
    revisiting. I wonder how a lot effort you place to make one of these excellent informative
    site.

Leave a Reply

Your email address will not be published.