-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathnews.dart
More file actions
29 lines (24 loc) · 855 Bytes
/
news.dart
File metadata and controls
29 lines (24 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'apikey.dart';
import '/models/modal_article.dart';
class News {
// String url = "https://newsapi.org/v2/everything?country=us&apiKey=$apiKey";
String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=$apiKey";
Future<List<Article>> getNews() async {
var response = await http.Client().get(Uri.parse(url));
if (response.statusCode == 200) {
Map<String, dynamic> _json = json.decode(response.body);
List<dynamic> body = _json['articles'];
List<Article> articles = [];
for (var element in body) {
try {
articles.add(Article.fromJson(element));
} catch (_) {}
}
return articles;
} else {
throw Exception("There was an error calling the API");
}
}
}