How do I append retrieved data to list from Firebase in flutter?

Viewed 51

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:

db_structure

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'],
  }
}
1 Answers

The problem is that you ArticleModel has a different fields name in the method .fromJson() from the data structure in the database, which is the dec key, you have written it in the model as desc.

So change:

description: element['desc'],

in ArticleModel to be:

description: element['dec'],
Related