I'm trying to create a function to return the articles list from the Firebase Realtime Database.
But it's not working. I'm new to flutter.
My Database structure is like the following:
Below is the code I have written for that:
Future<List<ArticleModel>> getArticles() async {
List<ArticleModel> articles = [];
uid = FirebaseAuth.instance.currentUser!.uid;
var ref = FirebaseDatabase.instance.ref().child("saved").child(uid);
await ref.once().then((DatabaseEvent databaseEvent) {
var docs = databaseEvent.snapshot.children;
for (var element in docs) {
Map<dynamic, dynamic> data = jsonDecode(jsonEncode(element.value));
var article = ArticleModel.fromJson(Map<dynamic, dynamic>.from(data));
articles.add(article);
}
});
print(articles);//Its printing [Instance of 'ArticleModel', Instance of 'ArticleModel'.......
return articles;
}
Code for ArticleModel
class ArticleModel {
String sourceName;
String author;
String title;
String description;
String url;
String urlToImage;
String publishedAt;
ArticleModel(
{required this.sourceName,
required this.author,
required this.title,
required this.description,
required this.urlToImage,
required this.url,
required this.publishedAt});
factory ArticleModel.fromJson(Map<dynamic, dynamic> element) {
return ArticleModel(
author: element['author'],
description: element['desc'],
sourceName: element['source'],
publishedAt: element['time'],
title: element['title'],
url: element['url'],
urlToImage: element['urlImage'],
}
}
