Untitled
unknown
plain_text
4 years ago
3.0 kB
22
Indexable
// View kısmı
class NewsScreen extends StatefulWidget {
const NewsScreen({Key? key}) : super(key: key);
@override
_NewsScreenState createState() => _NewsScreenState();
}
class _NewsScreenState extends State<NewsScreen> {
ApiService client = ApiService();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('News'),
),
body: Center(
child: FutureBuilder<News>(
future: client.fetchArticle(),
builder: (context, snapshot) {
print(snapshot.data);
if (snapshot.hasData) {
News? news = snapshot.data;
return ListView.builder(
itemCount: news!.articles.length,
itemBuilder: (context, index) {
return ListTile(
leading: Text(news.articles[index].author),
);
});
}
return CircularProgressIndicator();
},
),
),
);
}
}
// Model kısmı
class News {
News({
required this.status,
required this.totalResults,
required this.articles,
});
String status;
int totalResults;
List<Article> articles;
factory News.fromJson(Map<String, dynamic> json) => News(
status: json["status"],
totalResults: json["totalResults"],
articles: List<Article>.from(
json["articles"].map((x) => Article.fromJson(x))),
);
}
class Article {
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,
});
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
DateTime publishedAt;
String content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
source: Source.fromJson(json["source"]),
author: json["author"],
title: json["title"],
description: json["description"],
url: json["url"],
urlToImage: json["urlToImage"] == null ? null : json["urlToImage"],
publishedAt: DateTime.parse(json["publishedAt"]),
content: json["content"],
);
}
class Source {
Source({
required this.id,
required this.name,
});
String id;
String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"] == null ? null : json["id"],
name: json["name"],
);
}
// Service Kısmı
class ApiService {
Future<News> fetchArticle() async {
Uri uri = Uri.parse(
'https://newsapi.org/v2/everything?q=apple&from=2021-12-01&to=2021-12-01&sortBy=popularity&apiKey=f95feea2a9c8450eba38ca5559f699e7');
final response = await http.get(uri);
if (response.statusCode == 200) {
return News.fromJson(jsonDecode(response.body));
}else throw Exception('Failed');
}
}Editor is loading...