Learn how to create a simple news reader app using Flutter and a public news API. This step-by-step guide will teach you how to fetch and display news articles in a user-friendly interface.
In this exciting mini-project, we’ll guide you through building a simple news reader app using Flutter. This app will fetch the latest news articles from an online API and display them in a user-friendly list. By the end of this project, you’ll have a functional app that keeps you updated with the latest headlines!
The News Reader app will connect to a public news API to retrieve the latest news articles. We’ll display these articles in a scrollable list, complete with titles and brief descriptions. This project will introduce you to the world of APIs and how to use them to fetch data for your apps.
Let’s start by setting up our Flutter project:
Create a New Flutter Project: Open your terminal or command prompt and run the following command:
flutter create news_reader
Add the http
Package: Open the pubspec.yaml
file in your project and add the http
package under dependencies:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
Run flutter pub get
to install the package.
Set Up Internet Permissions: Ensure your app has permission to access the internet. For Android, check the AndroidManifest.xml
file in android/app/src/main/
and ensure it includes:
<uses-permission android:name="android.permission.INTERNET"/>
We’ll use a kid-friendly news API like NewsAPI.org. Follow these steps:
Sign Up for an API Key: Visit NewsAPI.org and sign up for a free developer account to obtain an API key.
Understand the API: Familiarize yourself with the API documentation to understand how to make requests and what data you can retrieve.
Define Dart classes to represent the news articles. This helps in organizing the data we fetch:
class Article {
final String title;
final String? description;
Article({required this.title, this.description});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
title: json['title'],
description: json['description'],
);
}
}
Write functions to send GET requests to the API and retrieve news data:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List<Article>> fetchNews() async {
final response = await http.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return (data['articles'] as List).map((json) => Article.fromJson(json)).toList();
} else {
throw Exception('Failed to load news');
}
}
Parse the JSON response and convert it into Dart objects, storing them in a list:
List<Article> articles = await fetchNews();
Use ListView.builder
to create a scrollable list of news articles:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('News Reader'),
),
body: ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(articles[index].title),
subtitle: Text(articles[index].description ?? ''),
),
);
},
),
);
}
Apply basic styling to make the app visually appealing:
AppBar
for the app’s title.Card
and Padding
for layout.Run the app on an emulator or device to ensure it correctly fetches and displays news articles. Debug any issues that arise during testing.
Consider adding features like:
Here’s the complete code for your News Reader app:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(NewsReaderApp());
class NewsReaderApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'News Reader',
home: NewsHomePage(),
);
}
}
class NewsHomePage extends StatefulWidget {
@override
_NewsHomePageState createState() => _NewsHomePageState();
}
class _NewsHomePageState extends State<NewsHomePage> {
List<Article> articles = [];
@override
void initState() {
super.initState();
fetchNews();
}
Future<void> fetchNews() async {
final response = await http.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
setState(() {
articles = (data['articles'] as List).map((json) => Article.fromJson(json)).toList();
});
} else {
throw Exception('Failed to load news');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('News Reader'),
),
body: ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(articles[index].title),
subtitle: Text(articles[index].description ?? ''),
),
);
},
),
);
}
}
class Article {
final String title;
final String? description;
Article({required this.title, this.description});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
title: json['title'],
description: json['description'],
);
}
}
Encourage readers to customize their news reader app by:
Include screenshots of the app at different stages to illustrate progress. Show the initial setup, after fetching data, and with added features.